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

Chaim Friedman picture Chaim Friedman · Feb 7, 2017 · Viewed 27.6k times · Source

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>
            )
        }
    }

Answer

jered picture jered · Feb 7, 2017

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]);
}