Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS convert blob url to Base64 file

Tags:

javascript

There is the following code:

console.log(blob);
var reader = new window.FileReader();
reader.onloadend = function() {            
  console.log(reader.result);
};
reader.readAsDataURL(blob);

blob is 'blob:http://localhost:3000/e3c23a22-75b1-4b83-b39a-75104d1909b9' and I've got the following error:

TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

How can I fix this error and convert Blob to Base64 encoded image? Thanks in advance!

like image 555
malcoauri Avatar asked Aug 29 '16 10:08

malcoauri


People also ask

How do I convert blob data to a file?

Files are Blobs, just tack on the meta properties and you're good to go. The default for a blob when uploading it is blob . So, I first extracted the name of the file I was cropping and then gave the same filename so the cropped file while uploading it to server by doing form. append("blob",blob, filename); .

Is blob Base64 encoded?

BLOBs and Base64 Encoding The reason is that BLOBs are treated in the same manner as strings because they have already been encoded by using base64 encoding before storage into a dictionary file.

How do I decode blob data?

Simply enter your data then push the decode button. For encoded binaries (like images, documents, etc.) use the file upload form a little further down on this page.


1 Answers

I know this is an old question, but I came across this problem lately and it took me a while to fix it. So I am going to answer the question in case anyone run into it again.

First, I think the naming of variable blob is very confusing. Blob URLs and Blob Object are different things. This answer does a very good job explaining what a Blob URL is. I think you should rename it as below.

var blobUrl = 'blob:http://localhost:3000/e3c2...'

Then, the function readAsDataURL of FileReader requires a Blob Object as its parameter. And what you give it is the variable blob, which is a Blob URL.

So what you need to do is:

  1. Recover the Blob Object that is used to create the Blob URL
  2. Use readAsDataURL to convert the recovered Blob Object to base64 url

Here is the code I find in this answer:

var blob = new Blob(["Hello, world!"], { type: 'text/plain' });
var blobUrl = URL.createObjectURL(blob);

var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';

xhr.onload = function() {
   var recoveredBlob = xhr.response;

   var reader = new FileReader;

   reader.onload = function() {
     var blobAsDataUrl = reader.result;
     window.location = blobAsDataUrl;
   };

   reader.readAsDataURL(recoveredBlob);
};

xhr.open('GET', blobUrl);
xhr.send();
like image 57
Sun Haoran Avatar answered Oct 26 '22 03:10

Sun Haoran