In this article I will show you how to implement multiple images files uploads directly to paperclip using DropzoneJS. Let’s run through this with me.
Create Rails Project
To create a Rails project; open up your terminal and type commands below:
We will add two gems to our Gemfile.
dropzonejs-rails gem is a helper gem that integrates DropzoneJS into our Rails app.
paperclip for processing image uploads.
Open up your
Gemfile and add in the lines listed below:
Now let’s run a bundle install to install the gems:
Create a Image Model
Now we will create a model to store our image information for Paperclip. Run the command below to create the image model and migrate the database:
Then add some code to Image model to tell paperclip we want to have an attachment attached. Open up your image model (
app/models/image.rb:) and add the code listed below:
1 2 3 4
Create a Images Controller
Then create an Images controller which will be used to display and allow the upload of our images. Run the command below to create this controller:
Then update our routes file to set up the routes for our images controller. Open up the routes file (
config/routes.rb) and modify it:
1 2 3 4
Then modify our Images controller to add logic to handle the file upload as well as listing each of the images. Open up the Images controller (
app/controllers/images_controller.rb) and modify it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
DropzoneJS expects a json return, so the create method returns a JSON success or failure based on whether the image was uploaded successfully or not.
Then add Bootstrap to our application. Open up your application layout (
app/views/layouts/application.html.erb)and modify it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Well, then create our views. First let’s create the index view (
app/views/images/index.html.erb). Open up your index view for the images controller and modify it:
1 2 3 4 5 6 7 8 9 10 11 12
app/views/images/index.js.erb for your images controller and add the code listed below:
Then create the partial that we reference in the previous code. Create a new partial called
app/views/images/_index.html.erb for your images controller and add the code listed below:
1 2 3 4 5
Then modify our application.css and add the dropzone css require. Open up your
app/assets/stylesheets/application.css file and modify it:
1 2 3 4 5
Then modify our application.js and add the dropzone js require. Open up your
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
So far so good, if you start your Rails server and navigate to http://localhost:3000 you will notice that you can drag and drop images onto the app. On certain browsers, such as Google Chrome, you can even drag and drop one or more folders of images onto the dropzone placeholder and have them upload. In addition you can also click the dropzone and select a file via the file selection screen. That’s it! See ya! :)