Javascript 使用 Axios 下载图像并将其转换为 base64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41846669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download an image using Axios and convert it to base64
提问by Hobbyist
I need to download a .jpg image from a remote server and convert it into a base64 format. I'm using axios as my HTTP client. I've tried issuing a git request to the server and checking the response.datahowever it doesn't seem to work like that.
我需要从远程服务器下载 .jpg 图像并将其转换为 base64 格式。我使用 axios 作为我的 HTTP 客户端。我试过向服务器发出 git 请求并检查response.data它,但它似乎不像那样工作。
Link to axios: https://github.com/mzabriskie/axios
axios 链接:https: //github.com/mzabriskie/axios
Link to base64 implementation: https://www.npmjs.com/package/base-64
链接到 base64 实现:https: //www.npmjs.com/package/base-64
I'm using NodeJS / React so atob/btoa doesn't work, hense the library.
我正在使用 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));
回答by sean-hill
This worked great for me:
这对我很有用:
function getBase64(url) {
return axios
.get(url, {
responseType: 'arraybuffer'
})
.then(response => Buffer.from(response.data, 'binary').toString('base64'))
}
回答by bjunc
There might be a better way to do this, but I have done it like this (minus the extra bits like catch(), etc.):
可能有更好的方法来做到这一点,但我已经这样做了(减去像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);
}
});
I have a suspicion that at least part of your problem might be server-side. Even without setting { responseType: "blob" }you should have had something in your response.dataoutput.
我怀疑您的问题至少有一部分可能是服务器端的。即使没有设置{ responseType: "blob" },您的response.data输出中也应该有一些东西。
回答by Ervi B
This is what works for me (with Buffer.from) -
这对我有用(与Buffer.from)-
axios
.get(externalUrl, {
responseType: 'arraybuffer'
})
.then(response => {
const buffer = Buffer.from(response.data, 'base64');
})
.catch(ex => {
console.error(ex);
});

