How to use FileReader with React? (getting a strange error)

删除回忆录丶 提交于 2019-12-12 18:28:27

问题


I have tried solutions from

How to use FileReader in React?

and gotten the same error as my code.

I'm trying to use the FileReader() in a react component.

class Home extends Component {

  onChange(e) {
    let files = e.target.files;
    console.log(files);
    let reader = new FileReader();
    reader.readAsDataURL(files[0]);

    reader.onload = e => {
      console.log(e.target.result);
    };
  }

  render() {
    return (
        <div onSubmit={this.onFormSubmit}>
          <h1>Upload File Here</h1>
          <input type="file" name="file" onChange={e => this.onChange(e)} />
        </div>

export default Home;

console.log(files) returns the uploaded file (if I run it without the rest of the onChange() code). When I run the whole thing, I get an error message of:

Error: cannot read as File: {} on reader.readAsDataURL(files[0]);

I'm following this tutorial exactly and it is working fine for them. Any thoughts?!

https://www.youtube.com/watch?v=sp9r6hSWH_o&t=50s


回答1:


Try this

Change

   onChange(e) {
        let files = e.target.files;
         console.log(files);
         let reader = new FileReader();
         reader.readAsDataURL(files[0]);

          reader.onload = e => {
              console.log(e.target.result);
          };
     }

To

    onChange = e => {
         let files = e.target.files;
         console.log(files);
         let reader = new FileReader();
         reader.onload = r => {
              console.log(r.target.result);
          };
         reader.readAsDataURL(files[0]);
     }


来源:https://stackoverflow.com/questions/54050401/how-to-use-filereader-with-react-getting-a-strange-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!