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

后端 未结 2 1296
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 12:46

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
    @tem         


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

    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

    0 讨论(0)
  • 2021-01-31 13:17

    this worked in my case:

      $('.file-input').on 'change', (event) ->
        $('.image').attr('src', URL.createObjectURL(this.files[0]))
    
    0 讨论(0)
提交回复
热议问题