gpt4 book ai didi

javascript - JS 函数返回 null - 帮助

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:21:35 25 4
gpt4 key购买 nike

我正在尝试修改示例 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;
}

感谢所有有用的评论:)

最佳答案

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

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

关于javascript - JS 函数返回 null - 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6632671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com