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

Hob*_*ist 36 javascript axios

我需要从远程服务器下载.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不起作用,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));
Run Code Online (Sandbox Code Playgroud)

小智 77

这对我很有用:

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

  • 谢谢,效果很好!如果您要将base64放在<img src =“” ...中,那么请不要忘记在base64字符串前面加上“ data:image / jpeg; base64,” (4认同)
  • 这工作得很好!如果可以,我会点赞 100 次! (2认同)
  • 如果您使用的是 `react-native`,请将其添加到文件的顶部:`global.Buffer = global.Buffer || 需要('缓冲区')。缓冲区` (2认同)
  • ** DeprecationWarning:由于安全性和可用性问题,不建议使用Buffer()。请改用Buffer.alloc(),Buffer.allocUnsafe()或Buffer.from()方法。** (2认同)
  • 应该是Buffer.from(response.data,'binary')) (2认同)
  • 对于使用react-script v5,您必须首先安装缓冲区依赖项。并导入它。```npm 安装缓冲区`` (2认同)

Erv*_*i B 18

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

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


小智 13

可能有更好的方法来做到这一点,但我已经这样做了(减去额外的比特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);

        }
    });
Run Code Online (Sandbox Code Playgroud)

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


小智 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" });
  })
Run Code Online (Sandbox Code Playgroud)