Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Reader telling me that parameter 1 is not a blob?

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>
            )
        }
    }
like image 341
Chaim Friedman Avatar asked Feb 07 '17 20:02

Chaim Friedman


1 Answers

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]);
}
like image 63
jered Avatar answered Nov 03 '22 08:11

jered