【问题标题】:Reading multiple files cotent's React JS读取多个文件cotent的React JS
【发布时间】:2020-10-06 18:58:07
【问题描述】:

我正在尝试使用 React.js 读取多个文件,但我的代码只读取一个文件,而没有读取其余文件。有什么建议吗?

谢谢

constructor(props) {
    super(props);
    this.state = {
        files: [],
        changedFileIndex: -1,
        fileReader : null
    };
    this.fileUploaderRef = React.createRef();
}

 handleFileReader = (e)=>{
    console.log("handleFileReader")
     var content =this.state.fileReader.result;
     console.log(content);
 }

  handleFileChosen(file){
    console.log("handleFileChosen")
    console.log(file.result)
     this.state.fileReader=new FileReader();
     this.state.fileReader.onloadend = this.handleFileReader;
     this.state.fileReader.readAsText(file);   

 }


async readAllFiles (AllFiles) {
    console.log("readAllFiles")
    //console.log(AllFiles[0].name)
   AllFiles.map((file)=>
       {  
               this.handleFileChosen(file)
        }
    );

 }

在文件数组中,我们需要遍历文件并发送给其他函数,以便将每个文件的内容写入数组中。 经过一些调试,例如对于 2 个文件,看起来代码执行 'handleFileChosen' 2 次,然后转到 handleFileReader 2 次,这可能是错误的,但我不知道如何解决这个问题。相反,它应该是这样的:执行 'HandleFileReader',然后执行 'handleFileChosen',然后再执行 'HandleFileReader',然后执行 'handleFileChosen'

【问题讨论】:

    标签: javascript reactjs file


    【解决方案1】:

    arr.map()synchronous 和 FileReader 工作 asynchronously,在 map 返回的数组上使用 Promise.all

    参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

    我已经修改了你的函数来读取所有文件

    handleFileChosen = async (file) => {
      return new Promise((resolve, reject) => {
        let fileReader = new FileReader();
        fileReader.onload = () => {
          resolve(fileReader.result);
        };
        fileReader.onerror = reject;
        fileReader.readAsText(file);
      });
    }
    
    
    readAllFiles = async (AllFiles) => {
      const results = await Promise.all(AllFiles.map(async (file) => {
        const fileContents = await handleFileChosen(file);
        return fileContents;
      }));
      console.log(results);
      return results;
    }
    
    【解决方案2】:

    请找到完整的代码来展示如何读取多个文件内容。在handleUpload 事件中,我准备了AllFiles 并通过传递AllFiles 调用函数readAllFiles。然后我在readAllFiles 下调用了readFileContents,它实际上是在读取文件内容。由于 FileReader 工作 asynchronously 所以需要在这里使用 Promise

    Here is Code Sandbox

    代码如下:

    import React, {Component} from 'react';
    
    export default class FileReaderExample extends Component {
    
        readFileContents = async (file) => {
            return new Promise((resolve, reject) => {
                let fileReader = new FileReader();
                fileReader.onload = () => {
                    resolve(fileReader.result);
                };
                fileReader.onerror = reject;
                fileReader.readAsText(file);
            });
        }
        readAllFiles = async (AllFiles) => {
            const results = await Promise.all(AllFiles.map(async (file) => {
                const fileContents = await this.readFileContents(file);
                return fileContents;
            }));
            console.log(results, 'resutls');
            return results;
        }
    
        handleUpload = (e) => {
            let AllFiles = [];
            [...e.target.files].map(file => AllFiles.push(file));
    
            this.readAllFiles(AllFiles).then(result => {
                let preview = document.getElementById('showText');
                let allFileContents = "";
                result.map(res =>{
                    allFileContents += res + '<br/>'
                })
                preview.innerHTML = allFileContents;
            })
                .catch(err => {
                    alert(err);
                });
        }
    
        render = () => {
    
            return (<div>
                    <input type="file" multiple onChange={(e) => this.handleUpload(e)}/>
                    <div id="showText">Choose text File</div>
                </div>
            )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 2020-02-13
      • 2021-09-01
      • 2018-07-12
      • 2022-12-02
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      相关资源
      最近更新 更多