14

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.

random
  • 10,238
  • 8
  • 57
  • 101

3 Answers3

23

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>
Puce
  • 1,003
  • 14
  • 28
  • I think it's using some HTML5 functionality, that's probably the cause. – Puce Sep 26 '13 at 14:32
  • IE do not have FileReader class – Rodrigo Sep 26 '13 at 18:01
  • 2
    @Puce for multiple images [MDN has a good example](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL). This MDN page also shows browser compatibility – BigRon Jul 08 '17 at 12:27
5

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.

davidmh
  • 1,368
  • 13
  • 24
1

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

<%= f.hidden_field :image_cache %>
Puce
  • 1,003
  • 14
  • 28
KennyVB
  • 745
  • 2
  • 9
  • 28
  • 2
    which document? any reference available? – Rubyrider Feb 19 '14 at 11:24
  • If you provide any reference to the document, it will be better. – learner Feb 13 '15 at 17:37
  • https://github.com/carrierwaveuploader/carrierwave#making-uploads-work-across-form-redisplays – Jason Galvin Mar 13 '15 at 02:42
  • 6
    This functionality is for redisplaying across submissions, not for previewing. – Greg Olsen Feb 01 '16 at 14:16
  • I used this functionality, but if a user goes to his profile to change say his last name for example, it requires him to upload again the picture, althought it was already loaded in a previous session, and the picture is visible. NOt sure how to handle. – Rene Chan Jul 28 '19 at 08:31