我需要从远程服务器下载.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)
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)
| 归档时间: |
|
| 查看次数: |
34270 次 |
| 最近记录: |