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

lam*_*rin 11 javascript ruby-on-rails

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

它适用于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;
}
Run Code Online (Sandbox Code Playgroud)

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

Nit*_*esh 7

在 ERB 中:获取输入,并给它一个类名和动态 ID,并制作一个带有动态 ID 的图像标签,您将在其中显示预览图片。

<%= f.file_field :photo, :class => 'photo_upload', :id => "image_#{image.id}" %>  
<%= image_tag("preview.png", :id => "image_#{image.id}_medium") %>
Run Code Online (Sandbox Code Playgroud)

在 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);
});
Run Code Online (Sandbox Code Playgroud)


Puc*_*uce 5

这个解决方案就像一个魅力,并且对 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>
Run Code Online (Sandbox Code Playgroud)

在 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>
Run Code Online (Sandbox Code Playgroud)


apn*_*ing 3

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

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

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

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

Firefox 兼容 HTML5...