Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 241
Tim Gerhard Avatar asked Dec 24 '19 07:12

Tim Gerhard


People also ask

How do I convert Blob data to a File?

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.

How can I convert Blob to JPG?

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.

How do I find the URL of a blob object?

let blob = await fetch(url). then(r => r. blob()); The url can be an object url or a normal url.


Video Answer


2 Answers

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);       
});
like image 137
Tim Gerhard Avatar answered Oct 21 '22 00:10

Tim Gerhard


set axios header :

axios.get(blobUrl, {
       responseType: 'blob'  /* or responseType: 'arraybuffer'  */         
})
.then(r => r.blob())
.then(blobFile => 
     new File([blobFile], fileName, { type: blobFile.type })
);
like image 23
Babak Yaghoobi Avatar answered Oct 21 '22 00:10

Babak Yaghoobi