Long Phan
Long Phan

Reputation: 338

Confused on blob:url and converting it to base64 in react-dropzone

I am using the package react-dropzone (https://github.com/okonet/react-dropzone) to get images from the user. The user uploads their image and everything is fine, but Im only getting something like "blob:http//blahblah" from it and I need the image to be in base64 png.

my dropzone component:

<Dropzone ref="dropzone" multiple={false} onDrop={this.onDrop.bind(this)} >
  {this.state.files ?<img className="img-responsive" src={this.state.files[0].preview}></img>
   : <div>Upload Photo</div> }
</Dropzone>

and the drop function that gets the blob url :

onDrop (files ) {
    if ( files.length === 0 ) {
        alert("upload img please")
        return;
    }
    console.log('Received files: ', files);
    this.setState({files:files})
    var blobURL = files[0].preview
    var reader = new FileReader();
    reader.readAsDataURL(blobURL)
  }

I would get an error :Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

I think it is because im trying to pass in an object-url that points to a blob, but where would I be able to get blob so I can convert to base64?

Upvotes: 3

Views: 8337

Answers (1)

magnump0
magnump0

Reputation: 2566

I would suggest to use a promise to get the result of async convertion by FileReader.readAsDataURL method. Here's the sample how it can be done:

const promise = new Promise((resolve, reject) => {
  const reader = new FileReader()

  reader.readAsDataURL(files[0])

  reader.onload = () => {
    if (!!reader.result) {
      resolve(reader.result)
    }
    else {
      reject(Error("Failed converting to base64"))
    }
  }

})
promise.then(result => {
  // dispatch or do whatever you need with result
}, err => {
  console.log(err)
})

Upvotes: 8

Related Questions