Rails + javascript – 上传前的图片预览

我想在上传之前显示图像预览,因为我使用下面给出的代码。

它适用于Firefox,但不适用于IE8

"preview-photo" %>  "preview(this);" %> function preview(this) { document.getElementById("preview-photo").src = this.value; return; } 

有没有解决方案在IE8和其他浏览器中预览图像?

我使用https://github.com/blueimp/jQuery-File-Upload进行文件上传。

在这个jQuery插件的规范中,你可以阅读:

可以在支持URL或FileReader接口的浏览器上为本地图像文件加载和显示预览图像。

IE8不符合HTML5,因此与FileReader不兼容。 您应该使用flash或朋友来实现这一目标。

Firefox符合HTML5标准……

此解决方案的工作方式类似于魅力,并且具有Internet Explorer的条件加载,因此它应该适合您。

我把代码放在这里,以防源死:

脚本:

   

在HTML中:

     your image  

在ERB中:获取输入,并为其指定一个类名和动态ID,并使用dyanamic id创建一个图像标记,您将在其中显示预览图片。

 <%= f.file_field :photo, :class => 'photo_upload', :id => "image_https://stackoverflow.com/questions/5593866/railsjavascript-image-preview-before-upload/#{image.id}" %> <%= image_tag("preview.png", :id => "image_https://stackoverflow.com/questions/5593866/railsjavascript-image-preview-before-upload/#{image.id}_medium") %> 

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

我为IE用户制作了一个纯粹的JS解决方案: http : //mootools.standupweb.net/dragndrop.php