- Read Tutorial
- Watch Guide Video
In this lesson, we are going to see how to create a file uploader and explore the different configuration options for building out a Carrierwave upload feature.
To start, go to your console and type the command
rails g uploader TaskFile
and this will create an uploader file for us.
Now, go to task_file_uploader.rb
and configure it to look like this:
If you notice, it already has a bunch of code loaded for us. At the top, you can see the name of the class is TaskFileUploader
and this inherits from CarrierWave, which comes from the Uploader and Base classes respectively. This means, it brings in the CarrierWave methods for us to use it on our file. It also brings in the CarrierWave::MiniMagick
and Sprockets::Rails::Helper
modules. If you see the comments before each code, you can know why it's here.
In the next line, you can see that it uses fog
for storage, and not the regular file system. It's important to not use the local file system especially heroku as it messes up the temporary files (aka randomly deletes them), so it's best to use fog
and connect to an outside service such as AWS.
The next method is store_dir
and in this method, you can see that it sets the name of the file. Since AWS uses a certain naming convention, the same is followed here, and the upload files are stored in the uploads
directory.
Next is the extension_white_list
method, and the %w
inside this method means that every one of these types present inside parentheses will become an element in a string array. You can also rewrite this as a regular Ruby array if that makes it easier for you, however this syntax is considered a best practice.
If you don't have any of these lines of code in your file, make sure to add them manually.