Upload an image using Axios and convert it to base64

I need to download a .jpg image from a remote server and convert it to base64 format. I use axios as my HTTP client. I tried to issue a git request to the server and check response.data , however it does not work like that.

Axios Link: https://github.com/mzabriskie/axios

Base64 implementation reference: https://www.npmjs.com/package/base-64

I am using NodeJS / React, so atob / btoa does not work, find out the library.

 axios.get('http://placehold.it/32').then(response => { console.log(response.data); // Blank console.log(response.data == null); // False console.log(base64.encode(response.data); // Blank }).catch(err => console.log(err)); 
+25
source share
3 answers

This worked fine for me:

 function getBase64(url) { return axios .get(url, { responseType: 'arraybuffer' }) .then(response => new Buffer(response.data, 'binary').toString('base64')) } 
+59
source

There may be a better way to do this, but I did it like this (minus extra bits like catch() , etc.):

 axios.get(imageUrl, { responseType:"blob" }) .then(function (response) { var reader = new window.FileReader(); reader.readAsDataURL(response.data); reader.onload = function() { var imageDataUrl = reader.result; imageElement.setAttribute("src", imageDataUrl); } }); 

I have a suspicion that at least part of your problem may be server-side. Even without setting { responseType: "blob" } , you should have had something in the output of response.data .

+10
source

This is what works for me (with Buffer.from ) -

 axios .get(externalUrl, { responseType: 'arraybuffer' }) .then(response => { const buffer = Buffer.from(response.data, 'base64'); }) .catch(ex => { console.error(ex); }); 
0
source

Source: https://habr.com/ru/post/1014405/


All Articles