Javascript 使用Axios下载图像并将其转换为base64
我需要从远程服务器下载一个.jpg图像,并将其转换为base64格式。我正在使用axios作为我的HTTP客户端。我曾尝试向服务器发出git请求并检查Javascript 使用Axios下载图像并将其转换为base64,javascript,axios,Javascript,Axios,我需要从远程服务器下载一个.jpg图像,并将其转换为base64格式。我正在使用axios作为我的HTTP客户端。我曾尝试向服务器发出git请求并检查响应.data,但它似乎不是这样工作的 链接到axios: 链接到base64实现: 我使用的是NodeJS/React,所以atob/btoa不起作用 axios.get('http://placehold.it/32').then(response => { console.log(response.data); // Blank
响应.data
,但它似乎不是这样工作的
链接到axios:
链接到base64实现:
我使用的是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));
也许有更好的方法可以做到这一点,但我是这样做的(减去额外的位,如
catch()
,等等):
我怀疑您的问题至少有一部分可能是服务器端的。即使没有设置
{responseType:“blob”}
您的响应.数据
输出中也应该有一些内容。可能有更好的方法,但我是这样做的(减去额外的位,如catch()
,等等):
我怀疑您的问题至少有一部分可能是服务器端的。即使没有设置
{responseType:“blob”}
您的响应.数据
输出中也应该有一些内容。这对我来说非常有用:
函数getBase64(url){
返回轴
.get(url{
响应类型:“arraybuffer”
})
.then(response=>Buffer.from(response.data,'binary').toString('base64'))
}
这对我来说非常有效: 函数getBase64(url){ 返回轴 .get(url{ 响应类型:“arraybuffer” }) .then(response=>Buffer.from(response.data,'binary').toString('base64')) } 这对我来说很有用(使用
Buffer.from
)-
这就是我的工作原理(使用Buffer.from
)-
您是否尝试将响应类型更改为blob?From docs“/
responseType
表示服务器将响应的数据类型:“您是否尝试将responseType更改为blob?”?From docs“/responseType
表示服务器将响应的数据类型“这非常好!如果可以的话,我会投100票!如果您使用的是react native
,请将其添加到文件顶部:global.Buffer=global.Buffer | | require('Buffer')。Buffer
谢谢,效果很好!如果将base64置于弃用状态警告:Buffer()由于安全性和可用性问题而弃用。请改用Buffer.alloc()、Buffer.allocUnsafe()或Buffer.from()方法。这应该是Buffer.from(response.data,'binary'))这很好用!如果可以的话,我会投100票!如果您使用的是react native
,请将其添加到文件顶部:global.Buffer=global.Buffer | | require('Buffer')。Buffer
谢谢,效果很好!如果将base64置于弃用状态警告:Buffer()由于安全性和可用性问题而弃用。请改用Buffer.alloc()、Buffer.allocUnsafe()或Buffer.from()方法。这应该是Buffer.from(response.data,'binary'))在搜索数小时后,我找到了解决方案。非常感谢。经过几个小时的搜索,我找到了解决办法。非常感谢。
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);
}
});
axios
.get(externalUrl, {
responseType: 'arraybuffer'
})
.then(response => {
const buffer = Buffer.from(response.data, 'base64');
})
.catch(ex => {
console.error(ex);
});