开发者

JS function returns null - help

I am trying to modify the example http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files to make function handleFileSelect(evt) return reader.result; I mean to make function return base64 for image or so. I tried to write it with function but it returns null only :( So my question is how to make the function return base64?

As for now I tried to write this snippet...

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;
  }

All useful comments are appreciated :)


I don't know the FileReader object in detail, but it looks like it reads data from a URL asynchronously. That means that when your function returns reader.result, the FileReader object isn't done reading the file yet. That doesn't finish until the onload callback is called (or some other error condition occurs).

So, your function returns while the reading is still happening asynchronously. Thus the result has not yet been determined. The result would be available on side the onload callback or (I'm guessing), inside other callbacks that would signify error conditions (onabort, onerror, etc..).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜