Some problems with uploading image files with rails + carrierwave.

Tram Ho

When I uploaded the file uploader function with gem rails, I encountered 3 small problems:

  • How to validate file extension on client side and server side?
  • How to preview the image right after selecting? I will share my solution in those 2 issues.

Create the form

First, remember that you have installed carrierwave:

Suppose I have a Article model with 2 title and thumbnail fields as follows:

Create routes, controllers and views for the form

I will add an initializers to add errors_message under each field in the form:

And we get a form as follows:

Validate file extension

Now, to make a validate extension of the file, I will share two ways:

  • Validate client side: Using javascript.
  • Validate model level: Use validate in carrierwave’s uploader class

To validate on the client side, we catch the onchange event in file_field as follows:

And add 1 javascript:

And it runs as follows:

But with the aforementioned way, when the browser turns off js, it becomes useless. Therefore, I usually perform validate at model level. Carrierwave provides you with the extension_whitelist method to validate the extension in the class CarrierWave::Uploader::Base .

Add I18n to the message:

And the validation part will run like this:

Preview the image file immediately after selecting it

To preview the image right after selecting the file (without uploading it to the server), first I will change the select file button a bit:

The image “default.png” you download here and put into assets / images. Add a little css:

And we get a field that selects the image as follows:

We use the FileReader class of js to perform the image preview function:

And the image preview function has completed:

I wrote the handleprevew(input_tag, image) function handleprevew(input_tag, image) in the easiest way to reuse. You just need to get the id of the input[type="file"] tag input[type="file"] and the id of its label image.

My article here is the end.


Share the news now

Source : Viblo