简体   繁体   English

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

[英]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.

相关问题 使用 FileReader.readAsText() 将 a.txt 文件拆分为 JavaScript 数组 - Splitting a .txt file into a JavaScript Array using FileReader.readAsText() HTML5 File API 中的 FileReader.readAsText 如何工作? - How FileReader.readAsText in HTML5 File API works? fileReader.readAsText()JavaScript:未显示结果 - fileReader.readAsText() javascript: result not displayed 来自“ HTML5 File API中的FIleReader.readAsText如何工作”的FileReader错误 - FileReader Error from “How FIleReader.readAsText in HTML5 File API works” 将FileReader.readAsText()结果字符串转换回文件对象以供下载? - Convert FileReader.readAsText() result string back into a file object for download? HTML5 文件 API:FileReader.readAsText() 返回“未定义” - HTML5 File API: FileReader.readAsText() returns "undefined" fileReader.readAsText 返回一个带引号的字符串 - fileReader.readAsText returns a string with quote 抛出&#39;FileReader&#39;的fileReader.readAsText():参数1不是&#39;Blob&#39;类型 - fileReader.readAsText() throwing 'FileReader': parameter 1 is not of type 'Blob' Cordova 文件插件 FileReader.readAsText 获取错误但不调用错误回调 - Cordova File plugin FileReader.readAsText gets error but does not call error callback 如何使用FileReader javascript读取XML文件? - How to read XML file using FileReader javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM