如何使用回形针在ruby轨道上立即预览上传的图像 [英] How to preview uploaded image instantly with paperclip in ruby on rails

查看:96
本文介绍了如何使用回形针在ruby轨道上立即预览上传的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想要完成的是允许用户在提交之前预览上传的图像。

Basically, what I want to accomplish is to allow user to preview their uploaded image before they submit it.

在控制器中,我有

def index
    @temp = Temp.new
end

由于@temp未保存,我是否还可以使用 Rails:Paperclip&预览的。如果没有,我可以运行javascript或其他东西来运行一些ruby代码吗?

Since @temp is not saved, can I still use the solution from Rails: Paperclip & previews. If not, can I run javascript or something to run some ruby code?

这是我的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 (:拇指)

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


推荐答案

如果我理解正确你想在它之前预览图像实际上已经上传了吧?您可以使用一些JavaScript来完成此操作。

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);
  });
});

和html:

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

你可以在代码笔

这篇关于如何使用回形针在ruby轨道上立即预览上传的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆