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

1 Answer 1

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]); } 
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much for taking the time to help me. Unfortunately, this code is producing the same error. I am going to try it in a fresh create-react-app to see if it makes any difference.
It worked when I created a new app. Very Strange! Thanks again for taking the time :)
I thought binding is the issue. Do you mean your old code worked?
Yes, both code worked when I created the new react app. Accepted your answer as it is also a solution to this problem should some other poor soul come along..
@HemadriDasari how can i set the state if this functionality is placed in my utils.csvreader.js file? unable to return a value on reader.onload function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.