Rails + javascript - 上传前的图像预览

问题描述:

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

它与Firefox,但不与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等浏览器的形象呢?

+0

你能后的HTML代码,浏览器会得到什么? – reporter 2011-04-08 12:22:15

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

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

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

IE8不符合HTML5,因此与FileReader不兼容。你应该使用闪光灯或朋友来实现这一点。

Firefox是兼容HTML5 ......

我现在已经把后备纯JS解决方案IE用户: http://mootools.standupweb.net/dragndrop.php

This解决方案的工作就像一个魅力和具有Internet Explorer的一个条件加载所以应该为你工作。

我把代码在这里,以防万一源模具:

脚本:

<!-- Assume jQuery is loaded --> 
<script> 
    function readURL(input) { 
    if (input.files && input.files[0]) { 
     var reader = new FileReader(); 

     reader.onload = function (e) { 
     $('#img_prev') 
      .attr('src', e.target.result) 
      .width(150) 
      .height(200); 
     }; 

     reader.readAsDataURL(input.files[0]); 
    } 
    } 
</script> 

在HTML:

<!--[if IE]> 
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
<![endif]--> 
</head> 
<body> 
    <input type='file' onchange="readURL(this);" /> 
    <img id="img_prev" src="#" alt="your image" /> 
</body> 
+0

不,它不工作在IE8 IE9 – 2014-03-11 17:58:50

+0

嘿puce,你通过包括原始链接做得很好。您已从原始链接中排除了'这行代码,并且代码正在工作只有这条线存在。你能帮我理解为什么这条线很重要吗? – learner 2015-02-13 15:23:59

+0

当然!我排除它,因为它是jQuery的负载。 jQuery是一个包装了一些函数的JavaScript库,并且(IMO)有助于使代码更加清晰(向专家询问更多技术性的解释)。具有'$('#img_prev')'这一事实意味着存在jQuery。问题是,在源代码中它加载了一个非常旧的jQuery版本,编码器应该尽可能地加载最新版本的jQuery。 无论如何,我会把一个评论,使其更清晰:) – Puce 2015-02-13 15:40:32

在ERB:取输入,并给它一个班级名称和动态ID,还可以制作带有dyanamic id的图像标签,您将在其中显示预览图片。

<%= f.file_field :photo, :class => 'photo_upload', :id => "image_#{image.id}" %> 
<%= image_tag("preview.png", :id => "image_#{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); 
});