简体   繁体   English

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

[英]Rails+javascript - image preview before upload

I want to show an image preview before upload, for that I am using the code given below. 我想在上传之前显示图像预览,因为我使用下面给出的代码。

It works with firefox, but doesn't work with IE8 它适用于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;
}

Is there any solution to preview the image in IE8 and other browsers? 有没有解决方案在IE8和其他浏览器中预览图像?

This solution works like a charm and has a conditional load for Internet Explorer so it should work for you. 解决方案就像一个魅力,并具有Internet Explorer的条件加载,因此它应该适合您。

I put the code here just in case the source dies: 我把代码放在这里,以防源死:

Script: 脚本:

<!-- 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>

In the HTML: 在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>

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

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

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

I do use https://github.com/blueimp/jQuery-File-Upload for file uploads. 我使用https://github.com/blueimp/jQuery-File-Upload进行文件上传。

In the spec of this jQuery plugin, you can read: 在这个jQuery插件的规范中,您可以阅读:

Preview images can be loaded and displayed for local image files on browsers supporting the URL or FileReader interfaces. 可以在支持URL或FileReader接口的浏览器上为本地图像文件加载和显示预览图像。

IE8 is not HTML5 compliant thus not compatible with FileReader. IE8不符合HTML5,因此与FileReader不兼容。 You should use flash or friends to achieve that. 您应该使用flash或朋友来实现这一目标。

Firefox is HTML5 compliant... Firefox符合HTML5标准......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM