【发布时间】:2021-11-20 10:48:34
【问题描述】:
我正在使用文件阅读器上传多个文件
我的目标是将每个文件的 base64 数据作为数组并输出到控制台。但是由于异步,我的代码总是显示空数组
当所有文件读取器都被完全读取后,如何显示base64数组?
我的代码在这里
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
var file;
var allfiles = [];
function uploadForm() {
Object.keys($('#file')[0].files).forEach(function(f){
reader = new FileReader()
console.log("---------")
reader.readAsDataURL( $('#file')[0].files[f]);
reader.onloadend = function(e) {
allfiles.push(e.target.result);
showMessage("Uploaded")
};
});
console.log(JSON.stringify(allfiles))
showMessage('Uploading file..<img width="20px;" src="https://c.tenor.com/XK37GfbV0g8AAAAi/loading-cargando.gif"/>');
}
/* Object.keys(files).forEach(function(f){
alert(files[f])
reader.readAsDataURL(files[f]);
})*/
function showMessage(e) {
$('#progress').html(e);
$('#file').val('');
}
</script>
<table cellpadding="5px">
<tr>
<td>Select File:</td>
<td>
<input id="file" type="file" value="" accept=".csv,.xlsx,.docx,.rtf,.pdf,.pptx,.txt" multiple>
</td>
</tr>
<tr>
<td colspan="2"><button onclick="uploadForm(); return false;">Upload</button> </td>
</tr>
<tr>
<td colspan="2">
<div id="progress"></div>
</td>
</tr>
</table>
【问题讨论】:
-
我按照您的建议进行了修改,但现在我遇到了这个问题(问题已修改)
标签: javascript html jquery file filereader