以下代码如何工作在IE8中上传多个文件?

时间:2013-04-29 11:15:16

标签: javascript html5 javascript-events internet-explorer-8

<!-- saved from url=(0022)http://internet.e-mail -->
<html>
<style>
  .thumb {
    height: 50%;
    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);

</script>
</html>

此代码在Mozila中工作正常。但它不能在IE8中工作,因为IE8不支持HTML5。有哪些必要的更改可以在IE8中正常工作?请提供详细信息............................................... .........

1 个答案:

答案 0 :(得分:0)

两个问题:

易:
IE8及以下版本不支持addEventListener,您需要调用attachEvent(请注意,这有一些问题,您需要查询全局事件对象,因为this未绑定到目标在这里!!)。

var el = document.getElementById('files');
if (el.addEventListener) {
  el.addEventListener('change', handleFileSelect, false); 
} else if (el.attachEvent)  {
  el.attachEvent('onchange', handleFileSelect);
}

棘手:
Filereader API在IE&lt; = 9中不可用,因此您需要使用flash或类似的东西(Silverlight ftw:-D)来解决这个问题。 Here's a list of shims。列表中还有一个Filereader垫片可能适合您。

最后,它可能是使用现有多上传脚本的最简单的解决方案。