使用 Axios 下载一个映像并将其转换为 base64

我需要下载一个。并将其转换为 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));
157431 次浏览

可能有一个更好的方法,但我是这样做的(减去额外的位,如 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输出。

这对我很有效:

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

这是什么为我工作(与 Buffer.from)-

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

您可以将 blob 从 文件阅读器 api 转换为 base64,然后显示它。

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

并将其展示为:

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

使用 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" });
})
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");