'Convert Blob URL to file object with axios

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: enter image description here

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.



Solution 1:[1]

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);       
});

Solution 2:[2]

set axios header :

axios.get(blobUrl, {
       responseType: 'blob'  /* or responseType: 'arraybuffer'  */         
})
.then(r => r.blob())
.then(blobFile => 
     new File([blobFile], fileName, { type: blobFile.type })
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Gerhard
Solution 2 Babak Yaghoobi