使用 Axios 下载图像并将其转换为 base64

IT技术 javascript axios
2021-03-11 04:11:50

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

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

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

我正在使用 NodeJS/React,所以 atob/btoa 不起作用,因此图书馆。

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));
4个回答

这对我很有用:

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'))
}
那应该是 Buffer.from(response.data, 'binary'))
2021-04-22 04:11:50
谢谢,效果很好!如果您将 base64 放在 <img src="" ... 然后不要忘记在 base64 字符串前加上“data:image/jpeg;base64,”
2021-04-23 04:11:50
如果您正在使用react-native,请将其添加到文件顶部:global.Buffer = global.Buffer || require('buffer').Buffer
2021-05-13 04:11:50
弃用警告:由于安全和可用性问题,不推荐使用 Buffer()。请改用 Buffer.alloc()、Buffer.allocUnsafe() 或 Buffer.from() 方法。
2021-05-15 04:11:50
这非常有效!如果可以,我会点赞 100 次!
2021-05-17 04:11:50

可能有更好的方法来做到这一点,但我已经这样做了(减去像catch()的额外位):

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

        }
    });

我怀疑您的问题至少有一部分可能是服务器端的。即使没有设置{ responseType: "blob" },您的response.data输出中也应该有一些东西

搜索了几个小时后,我找到了解决方案。谢谢!!
2021-04-19 04:11:50

这对我有用(与Buffer.from)-

axios
  .get(externalUrl, {
    responseType: 'arraybuffer'
  })
  .then(response => {
    const buffer = Buffer.from(response.data, 'base64');
  })
  .catch(ex => {
    console.error(ex);
  });

您可以将 Blob 从FileReader api转换为 base64 ,然后显示它。

 const fileReaderInstance = new FileReader();
 fileReaderInstance.readAsDataURL(blob); 
 fileReaderInstance.onload = () => {
 base64data = fileReaderInstance.result;                
 console.log(base64data);
 }

并将其显示为:

   <Image source={{uri: base64ImageData}} />