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

查看:107
本文介绍了使用 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 => Buffer.from(response.data, 'binary').toString('base64'))
}

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

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