Aditya Rohilla
Aditya Rohilla

Reputation: 337

How to upload a file from local in React?

I tried using the Filereader Html5 API, but in react it needs a npm module and the corresponding npm module for Filereader isn't working properly and showing error after file upload. Without doing require('Filereader'), webpack shows an error.

With npm module Filereader shows: "Uncaught Error: cannot read as File: {"preview":"blob:http%3A//dev.myntra.com%3A3000/cfb8a917-b3df-46b2-b055-21da34f253f2"}" Can i use some other npm module for this kind of file or is there any way i can use Filereader API directly from react? This is my code:

{
onDrop(files) {
  this.setState({
    files: files

  });
  console.log(files[0]);
  var reader = new FileReader();

  var contents;

   reader.onload = function(event) {

     contents = this.result;

     console.log(contents);

      $.ajax({
      type: 'POST',
      url: '/api/csv',
      async: true,
      data: json,
      crossDomain: true,
      contentType: "application/json; charset=utf-8",
      processData: false,
      timeout:5000,
      success: function(response){
        console.log("success");
      },
      error: function(jqXHR, textStatus){
        console.log("error");
        }            

      });

   }
        reader.readAsText(files[0],'utf8');



}




render() {
  return (
    <div>
    <Dropzone onDrop={this.onDrop}>
    <div>Try dropping some files here, or click to select files to upload.</div>
    </Dropzone>
    </div>
    );
}
}

Upvotes: 1

Views: 4080

Answers (1)

Aditya Rohilla
Aditya Rohilla

Reputation: 337

The problem got solved by using window.FileReader, through this i can access html5's Filereader API without using any npm package.

Upvotes: 3

Related Questions