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

148

我需要从远程服务器下载一个 .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));

1
你尝试过将responseType更改为blob吗?从文档中可以看到:“//responseType表示服务器将响应的数据类型”。 - Yury Tarabanko
6个回答

350

这对我非常有效:

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

4
非常好!如果可以的话,我会投100个赞! - mdev
3
如果你正在使用react-native,需要在你的文件顶部加入以下代码:global.Buffer = global.Buffer || require('buffer').Buffer。这段代码的作用是兼容react-native环境下的Buffer对象。 - ehacinom
17
谢谢,非常好用!如果你将base64放在<img src =“”...中,那么不要忘记在base64字符串前加上"data:image/jpeg;base64, "。 - mattdedek
5
DeprecationWarning: Buffer()已不再推荐使用,因为存在安全和可用性问题。请改用Buffer.alloc()、Buffer.allocUnsafe()或Buffer.from()方法。 - Nux
4
应该这样写:Buffer.from(response.data, 'binary') - Nux
显示剩余5条评论

38

可能有更好的方法来实现这个,但我是这样做的(除了像 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中有一些输出。


经过数小时的搜索,我终于找到了解决方案。谢谢! - Markus G.
非常好,谢谢。需要注意的是需要将事件监听器附加到“load”上。这对于在将数据读入FileReader实例后获取结果至关重要。 - Erutan409

26

这是对我有效的方式(使用Buffer.from) -

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

在我的情况下,需要的是 responseType: 'arraybuffer' - Codetard
responseType: 'arraybuffer' 表示响应类型为二进制数组,Buffer.from(response.data, 'binary') 用于下载 PDF 文件。 - xgqfrms

7

使用responseType: "text", responseEncoding: "base64"将获得以base64字符串编码的响应体。

例如,示例代码将获取base64并将jpg文件写入磁盘。

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

你可以使用FileReader API将Blob转换为Base64,然后进行显示。

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

并将其显示为:

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

OP要求使用axios,否则那是一个很好的浏览器解决方案! - zylo

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接