Rails 3: best way to preview image before upload

前端 未结 2 1977
感动是毒
感动是毒 2021-01-02 02:13

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?

相关标签:
2条回答
  • 2021-01-02 02:31

    HTML:

    <input type="file">
    <div id="image_preview"></div>
    

    JS (require jquery):

    $(document).ready(function(){
       $('input[type="file"]').change(function(){
         var image = window.URL.createObjectURL(this.files[0]);
         $("#image_preview").css("background-image", "url(" + image + ")");
       });
    });
    
    0 讨论(0)
  • 2021-01-02 02:40

    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. :) )

    0 讨论(0)
提交回复
热议问题