I have an image cropper that creates a blob file for each crop.
When the user finished cropping he clicks a success button and I get an URL that looks like this: blob:https://localhost:5001/4434606b-29c4-483d-a1fc-1cefe50a3e3a". Since I need a file object (so I can post it to my server) I convert this blob into an actual file object with this code:
const file = await fetch(blobUrl).then(r => r.blob()).then(blobFile => new File([blobFile], fileName, { type: blobFile.type }));
This code works, but unfortunately, I need to provide IE11 support and since fetch is not supported (and polyfills don't seem to work for this fetch call) I would like to migrate this statement into axios (which I already use all over my application).
This is what I've tried:
axios.get(blobUrl).then(r => r.blob()).then(blobFile => new File([blobFile], fileName, { type: blobFile.type }));
When I look at the response from the first call (then(r => r.blob()
) I get something like this:
I assume this is because the image can't be displayed in the console, but when I try to call "r.blob()" I get this:
r.blob is not a function
How can I change my axios call to work like the fetch call above?
Side note: I don't know which file type my response will have (except that it's an image), so it could be a png, jpg, gif etc.
To convert Blob to File in JavaScript, we can use the File constructor. const file = new File([myBlob], "name"); to create a File object with the myBlob blob object in the array. The 2nd argument is the file name string.
getContext("2d"); // Get the "context" of the canvas var img = document. getElementById("myimage"); // The id of your image container ctx. drawImage(img,0,0,width,height); // Draw your image to the canvas var jpegFile = canvas. toDataURL("image/jpeg"); // This will save your image as a //jpeg file in the base64 format.
let blob = await fetch(url). then(r => r. blob()); The url can be an object url or a normal url.
Apparently what I tried was a bit overkill. Here's the solution that worked for me:
const config = { responseType: 'blob' };
axios.get(blobUrl, config).then(response => {
new File([response.data], fileName);
});
set axios header :
axios.get(blobUrl, {
responseType: 'blob' /* or responseType: 'arraybuffer' */
})
.then(r => r.blob())
.then(blobFile =>
new File([blobFile], fileName, { type: blobFile.type })
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With