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.

4

3 回答 3

21

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>
于 2013-04-22T22:55:01.937 回答
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.

于 2012-08-20T18:23:20.083 回答
1

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

<%= f.hidden_field :image_cache %>
于 2012-12-21T17:31:08.267 回答