【问题标题】:View image before upload上传前查看图片
【发布时间】:2012-07-24 13:00:43
【问题描述】:

我需要在使用 jquery 上传之前显示上传图片,但在 chrome 路径中显示的假路径如下:

C:\fakepath\myImage.jpg

在 Firefox 中只显示文件名:

myImage.jpg

那么如何在上传之前预览我的图像文件

<input type="file">
<img src="" class="preview" />

如果那是不可能的……那么 HTML5 呢?

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

我不知道 jQuery 函数(抱歉),但 HTML5 可以,并且大多数浏览器都支持这个 HTML5 函数。在 HTML5rocks (1) 中找到一段代码:

<style>
  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }
</style>

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

祝你好运:)


(1) HTML5rocks - 读取文件:http://www.html5rocks.com/en/tutorials/file/dndfiles/

【讨论】:

    【解决方案2】:

    你不能。需要使用ajax上传图片,比如返回图片url,最后显示出来。

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      相关资源
      最近更新 更多