React-easy-crop just returns a blob url

2.6k views Asked by At

I am using react-easy-crop to allow users to modify their profile pictures after uploading. The problem I am experiencing is that after cropping, the image is returned in the form of a blob url like this: blob:http://localhost:3000/5e44190e-a087-4683-b3a4-dfce4a57ee62 which is unhelpful since it can only be viewed on my local machine.

I have tried converting it to a data url (which I understand can then be shared and viewed across browsers), using FileReader and the readAsDataURL() method like this:

let blob = await fetch(imageToCrop).then((r) => r.blob());
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
    let base64data = reader.result;
    console.log(base64data);
};

The base64data variable does return what I think I need, however all my attempts to then store this result in my state only return a null value.

Does anyone know what is the best way to handle this?

2

There are 2 answers

0
Nucasa On

If you have this line in your code, delete it because it revoke your URL.

window.URL.revokeObjectURL(this.fileUrl);
0
ValentinH On

If you need the base64 output of the cropped image, you can get it after using the canvas to crop it with canvas.toDataURL('image/jpeg'). This base64 string can then be shared to anyone or uploaded to a remote server.

This is basically the commented line in the getCroppedImg() function of this demo: https://codesandbox.io/s/q8q1mnr01w?file=/src/cropImage.js:2362-2562

BTW I guess you could also upload the blob to a remote server and store the image somewhere like AWS S3.