Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to show image previews before upload in rails & carrierwave

I've been using rails for past few days and wanted to know what is best way to show image previews before upload in rails & carrierwave.

I came across a few options like using plupload or jquery file upload or using uploadify.

like image 223
random Avatar asked Jul 14 '12 17:07

random


3 Answers

If you only need image preview in a form before upload, you (as me) will see that JQuery Upload plugin is just too much complex and not so easy to run properly (I was able to see the preview, but then I couldn't upload the picture).

http://saravani.wordpress.com/2012/03/14/preview-of-an-image-before-it-is-uploaded/

It's simple and fast to code.

I put the code here just in case the source dies:

Script:

    <!-- Assume jQuery is loaded -->
    <script>
      function readURL(input) {
        if (input.files && input.files[0]) {
          var reader = new FileReader();

          reader.onload = function (e) {
            $('#img_prev')
              .attr('src', e.target.result)
              .width(150)
              .height(200);
          };

          reader.readAsDataURL(input.files[0]);
        }
      }
    </script>

In the HTML:

    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    </head>
    <body>
      <input type='file' onchange="readURL(this);" />
      <img id="img_prev" src="#" alt="your image" />
    </body>
like image 118
Puce Avatar answered Nov 17 '22 00:11

Puce


You can use the plugin jQuery File Upload which it's a full solution, but if you need something less robust, you can also try using FileReader directly, like this, so you can customize the functionality to whatever you need.

like image 5
davidmh Avatar answered Nov 17 '22 00:11

davidmh


According to the documents image_cache is showing what you are uploading.

<%= f.hidden_field :image_cache %>
like image 1
KennyVB Avatar answered Nov 17 '22 00:11

KennyVB