如何在JavaScript中使用FileReader.readAsText同步读取文件



我正在尝试使用JavaScript中的FileReader.readAsText((读取CSV文件。但我无法同步获取值。我尝试了多种方法。但没有一个是有效的。以下是我迄今为止的代码:

第一种方法:

<input
id = "inputfile"
type = "file"
name = "inputfile"
onChange = {uploadFile} >
const uploadFile = (event: React.ChangeEvent < HTMLInputElement > ) => {
let resultSyncOutput = '';
connst files = event?.target.files;
if (files && files.length > 0) {
readAsTextCust(files[0]).then(resultStr => {
resultSyncOutput = resultStr;
});
}

// At this line I am not able to get the value of resultSyncOutput with the content of file sychronously

//Do something with the result of reading file.
someMethod(resultSyncOutput);
}
async function readAsTextCust(file) {
let resultStr = await new Promise((resolve) => {
let fileReader = new FileReader();
fileReader.onload = (e) => resolve(fileReader.result);
fileReader.readAsText(file);
});
console.log(resultStr);
return resultStr;
}

这是我尝试的第一种方法,即使用async/await。我也试着在没有aysnc/wait的情况下完成这项工作,但仍然没能成功。此操作的同步性至关重要。此外,项目中不允许使用Ajax。

注意:我在Stack Overflow中检查了很多答案,但没有一个能解决这个问题。因此,请不要将此标记为重复。任何地方都没有提供对这个特定问题的回答。

请帮助我,即使这对你来说很简单

我找到了解决方案resultSyncOutput=wait readAsTextCust(files[0](;并将调用函数声明为async有效。

您需要为onload事件回调设置一个回调函数来获取结果。还要注意,您需要对上载的CSV文件调用readAsText

您可以在输入的onChange回调中使用FileReaderAPI,方法如下:

<input
id = "inputfile"
type = "file"
name = "inputfile"
onChange = function (event: React.ChangeEvent<HTMLInputElement>) {
const reader = new FileReader();
reader.onload = (e) => {
console.log(e.target?.result) // this is the result string.
};
reader.readAsText(event.target.files?.[0] as File);
};

也不需要异步/等待。

最新更新