Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download an image using Axios and convert it to base64

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));
like image 785
Hobbyist Avatar asked Jan 25 '17 08:01

Hobbyist


People also ask

Can we convert image to Base64?

Convert Images to Base64Just select your JPG, PNG, GIF, Webp, or BMP picture or drag & drop it in the form below, press the Convert to Base64 button, and you'll get a base-64 string of the image. Press a button – get base64. No ads, nonsense, or garbage. Drag and drop your image here!


2 Answers

This worked great for me:

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'))
}
like image 88
sean-hill Avatar answered Oct 19 '22 13:10

sean-hill


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.

like image 32
bjunc Avatar answered Oct 19 '22 14:10

bjunc