How to upload multiple images in octobercms?

Member

by darion , in category: PHP CMS , a year ago

How to upload multiple images in octobercms?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , a year ago

@darion 

To upload multiple images in OctoberCMS, follow these steps:

  1. First, make sure you have installed the RainLab.Blog plugin. If not, go to the OctoberCMS backend, click on the "Marketplace" tab, search for "RainLab.Blog" in the search bar, and install it.
  2. Next, create or open a page or partial where you want to add the multiple image upload functionality. For example, let's assume you want to add it to the blog post creation form.
  3. In the page or partial markup, add the following code:
1
2
3
4
5
6
7
8
9
{% partial 'flashmessages' %}

<form method="POST" action="{{ 'blog/posts'|page }}">
    {{ form_token() }}
    
    <input type="file" name="images[]" multiple>
    
    <button type="submit">Upload</button>
</form>


Here, we have created a file input field with the name "images[]" allowing multiple file uploads. Adjust the form's action URL as per your requirements.

  1. In the relevant PHP section of your page or partial (e.g., in its controller class), handle the file upload and save it to the media directory:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use SystemModelsFile;

function onCreate()
{
    $images = post('images');

    if (!empty($images)) {
        foreach ($images as $image) {
            $file = new File;
            $file->data = $image;
            $file->save();

            // You can associate these files with your blog post or wherever needed
            $yourPost->featured_images()->attach($file);
        }
        
        Flash::success('Images uploaded successfully!');
    }
}


This onCreate() method will be called when the form is submitted. It retrieves the uploaded image files from the request's "images" field, saves them as File objects to the media directory, and associates them with your blog post (use this part based on your requirements).

  1. Lastly, to display the uploaded images, you can use the following code snippet:
1
2
3
{% for image in yourPost.featured_images %}
    <img src="{{ image.path }}" alt="">
{% endfor %}


Make sure to adjust "yourPost" and "featured_images" based on your blog post model and relation names.


That's it! This allows you to upload multiple images in OctoberCMS using the RainLab.Blog plugin.