简体   繁体   English

React Dropzone FileReader - 无法读取为文件:{}

[英]React Dropzone FileReader - cannot read as File: {}

I'm using the following code to retrieve data from a dropped/selected file.我正在使用以下代码从删除/选择的文件中检索数据。

onDrop = (files) => {
  files.forEach(file => {
    const reader = new FileReader();
    reader.onload = () => {
      const fileAsBinaryString = reader.result
      console.log(fileAsBinaryString);
    }
    reader.onabort = () => console.log('file reading was aborted');
    reader.onerror = () => console.log('file reading has failed');

    try {
      reader.readAsDataURL(file);
    } catch(err) {
      console.log(err)
      console.log(file);
    }

    this.setState({
      fileName: file.name
    })
  });
}

render() {
  return (
    <div className="app">
      <ReactDropzone onDrop={this.onDrop} className="dropzone">
        <IconContext.Provider value={{ size: "5em" }}>
          <IoMdCloudUpload/>
        </IconContext.Provider>
        <h1>{this.state.fileName}</h1>
      </ReactDropzone>
    </div>
  );
}

When I run the server and drop something inside the dropzone, even though console.log(file) gives me a non-blank File object, I get当我运行服务器并将某些内容放入 dropzone 时,即使 console.log(file) 给了我一个非空白的 File 对象,我也得到

Error: cannot read as File: {}

At

reader.readAsDataURL(file);

Any idea as to why this may happen and how I should fix it?关于为什么会发生这种情况以及我应该如何解决它的任何想法?

onDrop = (acceptedFiles, rejectedFiles) => {
        const reader = new FileReader()

        reader.readAsDataURL(acceptedFiles[0])

        reader.onload = () => {
            if (!!reader.result) {
                console.log('reader.result', reader.result)
            }
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM