使用Axios下载图像并将其转换为base64 [英] Download an image using Axios and convert it to base64

查看:786
本文介绍了使用Axios下载图像并将其转换为base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从远程服务器下载.jpg图像并将其转换为base64格式。我正在使用axios作为我的HTTP客户端。我已经尝试向服务器发出一个git请求并检查 response.data 然而它似乎不像那样工作。

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.

链接到axios: https://github.com/ mzabriskie / axios

链接到base64实现: https://www.npmjs.com/package/base-64

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

我正在使用NodeJS / React所以atob / btoa没有没事,图书馆。

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


推荐答案

这对我很有用:

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

这篇关于使用Axios下载图像并将其转换为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆