简体   繁体   English

如何使用 ruby​​ on rails 中的回形针即时预览上传的图像

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

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
    @temp = Temp.new
end

Since @temp is not saved, can I still use the solution from Rails: Paperclip & previews .由于 @temp 未保存,我是否仍然可以使用Rails: Paperclip & previews 中的解决方案。 If not, can I run javascript or something to run some ruby code?如果没有,我可以运行 javascript 或其他东西来运行一些 ruby​​ 代码吗?

This is my html:这是我的 html:

= form_for @temp, :url => temp_path, :html => { :multipart => true } do |form| = form_for @temp, :url => temp_path, :html => { :multipart => true } do |form|

 = form.file_field :image

= image_tag @temp.image.url = image_tag @temp.image.url

= image_tag @temp.image.url(:medium) = image_tag @temp.image.url(:medium)

= image_tag @temp.image.url(:thumb) = image_tag @temp.image.url(:thumb)

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.您可以通过使用一些 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:和 html:

<form>
  <input type="file" id="pictureInput"> 
</form>
<div id="target">
</div>

you can check it out on code pen你可以在代码笔上查看

this worked in my case:这在我的情况下有效:

  $('.file-input').on 'change', (event) ->
    $('.image').attr('src', URL.createObjectURL(this.files[0]))

No need for jQuery.不需要 jQuery。 You can do the same thing in modern JS:你可以在现代 JS 中做同样的事情:

const selectElement = document.querySelector('#pictureInput');

selectElement.addEventListener('change', (event) => {
  let files = event.target.files;
  let image = files[0]
  let reader = new FileReader();
  reader.onload = function(file) {
    let img = new Image();
    console.log(file);
    img.src = file.target.result;
    let target = document.querySelector('#target')
    while (target.firstChild) {
      target.removeChild(target.firstChild);
    }
    document.querySelector('#target').appendChild(img)
  }
  reader.readAsDataURL(image);
  console.log(files);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM