4

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

Hanley Soilsmith
  • 579
  • 2
  • 9
  • 27

1 Answers1

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]);
     }
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162