簡體   English   中英

如何在 JavaScript 中同步使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM