147

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));
1
  • 1
    Have you tried to change responseType to say blob? From docs "// responseType indicates the type of data that the server will respond with" Jan 25, 2017 at 8:47

6 Answers 6

347

This worked great for me:

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'))
}
10
  • 4
    This works perfectly well! I would upvote 100 times if I could!
    – mdev
    Oct 24, 2018 at 14:54
  • 3
    if you're using react-native, add this to the top of your files: global.Buffer = global.Buffer || require('buffer').Buffer
    – ehacinom
    Jan 30, 2019 at 20:22
  • 17
    Thank you, works great! If you're putting the base64 in <img src="" ... then don't forget to prefix the base64 string with "data:image/jpeg;base64, "
    – mattdedek
    Feb 7, 2019 at 0:19
  • 5
    DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
    – Nux
    Jun 25, 2019 at 18:45
  • 4
    that should be Buffer.from(response.data, 'binary'))
    – Nux
    Jun 25, 2019 at 18:51
37

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.

2
  • after searching for hours I found the solution. Thank you!!
    – Markus G.
    Feb 5, 2020 at 14:45
  • Very nice, thank you. Something for others to pay attention to is needing to attach an event listener to load. This is essential for getting the result after reading the data into the FileReader isntance.
    – Erutan409
    Oct 14, 2022 at 19:55
25

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);
  });
2
  • responseType: 'arraybuffer' was what needed in my case!
    – Codetard
    Dec 23, 2021 at 4:58
  • responseType: 'arraybuffer' and Buffer.from(response.data, 'binary') for download the pdf file.
    – xgqfrms
    Apr 26 at 15:21
6

using responseType: "text", responseEncoding: "base64" will get response body encoded as base64 string

for example, the sample code will get base64 and write a jpg file to disk.

import axios from "axios";
import fs from "fs";

axios
  .get("https://picsum.photos/255", {
    responseType: "text",
    responseEncoding: "base64",
  })
  .then((resp) => {
    console.log(resp.data);
    fs.writeFileSync("./test.jpg", resp.data, { encoding: "base64" });
  })
3

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}} />
1
  • OP requested axios, otherwise that's a great solution for the browser!
    – zylo
    Aug 18, 2022 at 20:56
2
import { Axios } from "axios";

const axios = new Axios({});

const res = await axios.get(url, {
  responseType: "text",
  responseEncoding: "base64",
});

const base64 = Buffer.from(res.data, "base64");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.