Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 views
in Technique[技术] by (71.8m points)

javascript - 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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This worked great for me:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...