Download an image using Axios and convert it to base64

JavascriptAxios

Javascript Problem Overview


I need to download a .jpg image from a remote server and convert it into a base64 format. I'm using axios as my HTTP client. I've tried issuing a git request to the server and checking the response.data however it doesn't seem to work like that.

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

Link to base64 implementation: https://www.npmjs.com/package/base-64

I'm using NodeJS / React so atob/btoa doesn't work, hense 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));

Javascript Solutions


Solution 1 - Javascript

This worked great for me:

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

Solution 2 - Javascript

There might be a better way to do this, but I have done it like this (minus the 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 might be server-side. Even without setting { responseType: "blob" } you should have had something in your response.data output.

Solution 3 - Javascript

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

Solution 4 - Javascript

You can convert the blob to base64 from FileReader api and then display it.

 const fileReaderInstance = new FileReader();
 fileReaderInstance.readAsDataURL(blob); 
 fileReaderInstance.onload = () => {
 base64data = fileReaderInstance.result;                
 console.log(base64data);
 }

and display it as:

   <Image source={{uri: base64ImageData}} />

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHobbyistView Question on Stackoverflow
Solution 1 - Javascriptsean-hillView Answer on Stackoverflow
Solution 2 - JavascriptbjuncView Answer on Stackoverflow
Solution 3 - JavascriptErvi BView Answer on Stackoverflow
Solution 4 - JavascriptMahmoud AzizView Answer on Stackoverflow