How to convert data returned by fetch into blob ? [Solved] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to convert data returned by fetch into blob ? [Solved]

So in the following code,I try to return text when response is received and then create a blob out of it , to use as a url with the help of URL.createObject... . But for some reason it doesn't works , why so? ty! And if I return blob instead of text then it works fine but converting text to blob don't !! https://code.sololearn.com/Wn79S1v1N7is/?ref=app

14th Feb 2021, 5:06 PM
Abhay
Abhay - avatar
2 Answers
+ 4
Does the following work the way you want? It shows the image when I run it in Google Chrome and it uses res.blob() instead of res.text(): const url="https://cors-anywhere.herokuapp.com/" fetch(url+"https://media.tenor.com/images/e483b4eedc03b276947beb32e9b0e4c6/tenor.gif") .then(res=>res.blob()) .then(blob=>{ var reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { var dataUrl=reader.result; var i=document.querySelector("img"); i.src=dataUrl; } }) I used the variable name dataUrl instead of url to clarify that your constant "url" is different. If you convert to text, you can introduce character encodings on data that isn't meant to be characters. A sequence of bytes doesn't map to 1 character per byte necessarily which can introduce problems. Unless you have a specific reason to use res.text(), res.blob() is more recommended for this raw binary data. My example above does create the base-64 encoded URL that you probably want.
15th Feb 2021, 7:13 AM
Josh Greig
Josh Greig - avatar
+ 1
Josh Greig ty i understand now , it is working fine with res.blob(). Actually i am using http response in node js to fetch data and then concatenate those chunks into a string , so i was checking here to see if the text converted to blob will work fine and so i would have then consider using blob module but seems like i need to think of a different way now.
15th Feb 2021, 7:38 AM
Abhay
Abhay - avatar