Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  122] [ 3]  / answers: 1 / hits: 55258  / 7 Years ago, tue, february 7, 2017, 12:00:00

I have a file input which returns what looks like a file path to me, and yet the fileReader is giving me the following error.



Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.


I feel like I am missing something here. Where am I going wrong?



import React from 'react';

export default class TestPage extends React.Component {
constructor() {
super();
this.state = {
file: ''
}
}

onChange(e) {
let reader = new FileReader();
reader.onload = function(e) {
this.setState({file: reader.result})
}
reader.readAsDataURL(e.target.value);
}

render() {
return (
<div>
<input onChange={this.onChange.bind(this)} type=file name=file />
<br />
<video width=400 controls>
<source src={this.state.file} type=video/mp4 />
</video>
</div>
)
}
}

More From » reactjs

 Answers
21

The answer is pretty obvious, it's right there in the error. Parameter 1 is not of type Blob - in other words, readAsDataURL expects a Blob but that's not what you're passing it. readAsDataURL is specifically meant to read Files or Blobs, not file paths. Meanwhile, the FileReader.result parameter will end up being a String or ArrayBuffer.



What you probably want to do is pass in the input files array, not e.target.value, to readAsDataURL.



onChange(e) {
let reader = new FileReader();
reader.onload = function(e) {
this.setState({file: reader.result})
}
reader.readAsDataURL(e.target.files[0]);
}

[#59037] Saturday, February 4, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
casandra

Total Points: 334
Total Questions: 93
Total Answers: 104

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
casandra questions
Thu, Feb 25, 21, 00:00, 3 Years ago
Mon, Jul 6, 20, 00:00, 4 Years ago
Thu, May 21, 20, 00:00, 4 Years ago
Tue, Sep 17, 19, 00:00, 5 Years ago
;