Rails + javascript - 上传前的图片预览 [英] Rails+javascript - image preview before upload
本文介绍了Rails + javascript - 上传前的图片预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在上传之前显示图片预览,因为我使用下面给出的代码。
I want to show an image preview before upload, for that I am using the code given below.
它适用于firefox,但不适用于IE8
It works with firefox, but doesn't work with IE8
<%= image_tag @image, :id=>"preview-photo" %>
<%= file_field 'image','photo', :onchange => "preview(this);" %>
function preview(this) {
document.getElementById("preview-photo").src = this.value;
return;
}
是否有任何解决方案可以在IE8和其他浏览器中预览图像?
Is there any solution to preview the image in IE8 and other browsers?
推荐答案
在ERB中:获取输入,并为其指定一个类名和动态ID,并使用dyanamic id创建一个图像标记将显示预览图片。
In ERB: Take input, and give it a class name and dynamic id, and also make a image tag with dyanamic id where you will show the preview pic.
<%= f.file_field :photo, :class => 'photo_upload', :id => "image_#{image.id}" %>
<%= image_tag("preview.png", :id => "image_#{image.id}_medium") %>
在JAVASCRIPT中:
In JAVASCRIPT:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(document.getElementById(input.id + "_medium")).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".photo_upload").change(function(){
readURL(this);
});
这篇关于Rails + javascript - 上传前的图片预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文