![](/img/trans.png)
[英]Splitting a .txt file into a JavaScript Array using FileReader.readAsText()
[英]How to read file using FileReader.readAsText synchronously in JavaScript?
我正在尝试使用 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/await 的情况下做到这一点,但仍然无法成功。 此操作必须是同步的,这一点至关重要。 项目中也不允许使用 Ajax。
注意:我在 Stack Overflow 中检查了很多答案,但没有一个提供解决此问题的方法。 所以请不要将此标记为重复。 任何地方都没有提供对这个特定问题的答案。
请帮助我,即使这对你来说看起来很简单
您需要为onload事件回调设置回调 function 以获得结果。 另请注意,您需要在上传的 CSV 文件上调用readAsText 。
您可以通过这种方式在输入的 onChange 回调中使用FileReader API:
<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);
};
也不需要异步/等待。
我找到了解决方案 resultSyncOutput = await readAsTextCust(files[0]); 并将调用 function 声明为异步工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.