Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preview uploaded image instantly with paperclip in ruby on rails

Basically, what I want to accomplish is to allow user to preview their uploaded image before they submit it.

In the controller, i have

def index
    @temp = Temp.new
end

Since @temp is not saved, can I still use the solution from Rails: Paperclip & previews. If not, can I run javascript or something to run some ruby code?

This is my html:

= form_for @temp, :url => temp_path, :html => { :multipart => true } do |form|

   = form.file_field :image

= image_tag @temp.image.url

= image_tag @temp.image.url(:medium)

= image_tag @temp.image.url(:thumb)

like image 261
donkey Avatar asked Aug 24 '14 17:08

donkey


1 Answers

If I understand you correctly you want to preview an image before it is actually uploaded, right? You can do so by using some javascript.

By setting the width and height attributes of the image tag you can simulate a thumbnail.

$(function() {
  $('#pictureInput').on('change', function(event) {
    var files = event.target.files;
    var image = files[0]
    var reader = new FileReader();
    reader.onload = function(file) {
      var img = new Image();
      console.log(file);
      img.src = file.target.result;
      $('#target').html(img);
    }
    reader.readAsDataURL(image);
    console.log(files);
  });
});

and the html:

<form>
  <input type="file" id="pictureInput"> 
</form>
<div id="target">
</div>

you can check it out on code pen

like image 132
TimKaechele Avatar answered Oct 20 '22 01:10

TimKaechele