3

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?

Long Phan
  • 328
  • 1
  • 9
  • 19
  • Could you clarify what you'll be using the data URL for? Blob URLs and data URLs are mostly interchangable. If you want to get the data itself to send to a server for instance, neither format is particularly ideal. For instance you can set the `` `src` to the Blob URL directly without getting a data URL. – loganfsmyth Nov 02 '16 at 00:30
  • Im trying to pass the actual base 64 encoded image png to my backend, it doesnt accept a data URL or blob URL. Is there anyway to get the actual blob from a data or blob url so i can then convert to base 64? – Long Phan Nov 02 '16 at 16:02
  • 1
    Cool. Seems like a duplicate of https://stackoverflow.com/questions/11876175/how-to-get-a-file-or-blob-from-an-object-url then? It's a URL, so you can make an XHR request to the URL to get the actual data, just like any other URL. Once you have that blob, you can send it to your server directly as binary data. – loganfsmyth Nov 02 '16 at 16:13

1 Answers1

8

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)
})
boldnik
  • 2,547
  • 2
  • 27
  • 32