1

尝试做一些我觉得应该相对直截了当的事情。

我只想读取文本文件内容并将其存储在变量中。

这是我的代码:

readToCSV(file) {
// console.log(file);

    let cat = "";

    var reader = new FileReader();
    reader.onloadend = function (event) {
        if (event.target.readyState == FileReader.DONE) {
            var data = event.target.result;
        }
        console.log("data:", data)
        cat = data;
    };

    reader.readAsText(file)
    console.log("cat:",cat);


};

我几乎尝试了所有方法,并且在函数之外一直未定义。我是否只需要在 onloadend 函数中嵌套任何进一步的处理。这似乎很愚蠢。

4

2 回答 2

1

I just want to read a text files content and store it in a variable.

The way you're currently doing it, cat will be an empty string because of the async nature of the FileReader.

I would do it with a callback.

var cat = '';
const reader = new FileReader();
reader.readAsText(document.querySelector('input[type="file"]').files[0]);
reader.onload = () => storeResults(reader.result);

function storeResults(result) {
  cat = result;
}

This way you get the job done and don't have to nest further processing directly within onloadend.
Hope that helps!

于 2018-11-04T19:55:50.863 回答
1

好的,所以我找到了一个解决方法,并想将它发布给其他试图将 fileContents 转换为可验证文件的人(说真的,为什么这么难)

无论如何,我最终将读者包装在一个承诺中并将其存储起来。

无论如何,新代码如下:

async handleFileUpload(e){
    console.log("e",e)
    await this.setState({file:e[0]})
    console.log("state: ",this.state.file)
       const fileContents = await this.readToText(this.state.file)
       console.log("fc:",fileContents);
    //await this.readToCSV(fileContents)
}

async readToText(file) {

    const temporaryFileReader = new FileReader();

    return new Promise((resolve, reject) => {
        temporaryFileReader.onerror = () => {
            temporaryFileReader.abort();
            reject(new DOMException("Problem parsing input file."));
        };

        temporaryFileReader.onload = () => {
            resolve(temporaryFileReader.result);
        };
        temporaryFileReader.readAsText(file);
    });

};
于 2018-11-04T19:57:26.180 回答