[英]How to read file using FileReader.readAsText synchronously in JavaScript?
I am trying to read a CSV file using FileReader.readAsText() in JavaScript.我正在尝试使用 JavaScript 中的 FileReader.readAsText() 读取 CSV 文件。 But I am not able to get the value synchronously.但我无法同步获得价值。 I tried multiple approaches.我尝试了多种方法。 But none is working.但没有一个工作。 Below is the code I have so far:以下是我到目前为止的代码:
1st Approach:第一种方法:
<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;
}
This is the first approach I tried ie, using async/await.这是我尝试的第一种方法,即使用 async/await。 I also tried to do it without aysnc/await and still was not able to succeed.我也尝试在没有 aysnc/await 的情况下做到这一点,但仍然无法成功。 It is critical for this operation to be synchronous.此操作必须是同步的,这一点至关重要。 Also use of Ajax is not allowed in project.项目中也不允许使用 Ajax。
NB: I checked a lot of answers in Stack Overflow and none provides a solution to this problem.注意:我在 Stack Overflow 中检查了很多答案,但没有一个提供解决此问题的方法。 So please do not mark this as duplicate.所以请不要将此标记为重复。 Answer to this particular question is not provided anywhere.任何地方都没有提供对这个特定问题的答案。
Please help me even if this looks simple to you请帮助我,即使这对你来说看起来很简单
You need to set a callback function for the onload event callback to get the results.您需要为onload事件回调设置回调 function 以获得结果。 Also notice that you need to call readAsText on the uploaded CSV file.另请注意,您需要在上传的 CSV 文件上调用readAsText 。
You can use FileReader API inside input's onChange callback this way:您可以通过这种方式在输入的 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);
};
No need for async/await as well.也不需要异步/等待。
I found the solution resultSyncOutput = await readAsTextCust(files[0]);我找到了解决方案 resultSyncOutput = await readAsTextCust(files[0]); and declaring the calling function as async worked.并将调用 function 声明为异步工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.