Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: best way to preview image before upload

I need to preview an image prior to submitting a form. I work with Rails 3 and needs something that is browser compatible. Any ideas how I can achieve that?

like image 902
Henri Avatar asked Aug 12 '13 14:08

Henri


People also ask

How do I preview multiple images before uploading?

Step 1. Make a HTML file and define markup and scripting. In this step we create a form to upload and preview multiple images then we create a file tag and add 'multiple' it allows to select multiple images and attach onchange event to call preview_image() function to preview all the images after user select the images ...

How do I preview an image before uploading HTML?

html. We have two main elements that we will interact with using JavaScript. First, we have a division element that contains the “img” tag. Using Jquery, we will change the “src” attribute of the “img” tag on upload to preview the image.


1 Answers

So! :) The main idea is to use the FileReader Javascript Class, which is really handy for what you need to do.

You just have to listen to the "change" event on your file input and then call a method that will use the "readAsDataURL()" method of the FileReader class. Then you just have to fill the source of a "preview img tag" with the returned result of the method...

I've wrote you a simple jsFiddle that achieves what you want. You can see my code below:

<!-- HTML Code -->
<div class="upload-preview">
    <img />
</div>
<input class="file" name="logo" type="file">    
//JS File
$(document).ready(function(){
    var preview = $(".upload-preview img");

    $(".file").change(function(event){
       var input = $(event.currentTarget);
       var file = input[0].files[0];
       var reader = new FileReader();
       reader.onload = function(e){
           image_base64 = e.target.result;
           preview.attr("src", image_base64);
       };
       reader.readAsDataURL(file);
    });
});

And in the Mozilla Documentation, you have another example (surely more robust). This solution should work with Safari (version 6.0+).

This is the only way I know to preview an image prior to submitting a form, but I think it is quite a common way. Of course it has nothing to do with Ruby On Rails as we only use Javascript here... It would be impossible to do it using Rails only as you would have to upload the image before rendering it. (As Rails is server side, I think you perfectly understand why. :) )

like image 121
Kulgar Avatar answered Sep 18 '22 10:09

Kulgar