4

我正在尝试修改示例http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files以使函数 handleFileSelect(evt) 返回 reader.result; 我的意思是让函数返回base64的图像左右。我试图用函数编写它,但它只返回 null :( 所以我的问题是如何让函数返回 base64?

至于现在我试着写这个片段......

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="', theFile.name, '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

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

感谢所有有用的评论:)

4

1 回答 1

2

我不详细了解 FileReader 对象,但它看起来像是从 URL 异步读取数据。这意味着当您的函数返回 reader.result 时,FileReader 对象尚未完成对文件的读取。在调用 onload 回调(或发生其他一些错误情况)之前,这不会完成。

因此,您的函数在读取仍在异步发生时返回。因此,结果尚未确定。结果将在 onload 回调或(我猜)在其他表示错误条件(onabort、onerror 等)的回调中可用。

于 2011-07-09T05:03:06.650 回答