Javascript 在React中使用Axios下载图像?
我正在尝试使用Axios中的GET请求下载图像,然后将其下载到用户PC。我需要使用Axios,因为GET请求具有授权标头 下面是我下载图像并将其存储为blob的功能:Javascript 在React中使用Axios下载图像?,javascript,reactjs,axios,Javascript,Reactjs,Axios,我正在尝试使用Axios中的GET请求下载图像,然后将其下载到用户PC。我需要使用Axios,因为GET请求具有授权标头 下面是我下载图像并将其存储为blob的功能: return axios({ method: 'GET', headers: { Authorization: `Bearer ${jwt}` }, url: `https://example.com/api/${url}`, responseType: 'blob' }) .then(response =>
return axios({
method: 'GET',
headers: { Authorization: `Bearer ${jwt}` },
url: `https://example.com/api/${url}`,
responseType: 'blob'
})
.then(response => {
if (response) {
const file = new Blob([response.data], {type:'image/png'})
return file
}
return Promise.reject('An unknown error occurred');
});
然后,我使用FileSaver保存以下内容:
const image = await userService.downloadImage(slug, this.props.token);
FileSaver.saveAs(image, "image.png")
我得到的是一个错误,下载文件时说
“失败-网络错误”
如果我查看Chrome的developer选项,我可以看到对API的GET请求,在preview选项卡中,我可以看到图像
关于我哪里出了问题,有什么建议吗?这意味着axios可以正常工作,但文件保护程序不会下载 查看,您可以看到支持的浏览器: 因此,请尝试升级当前浏览器或使用其他浏览器进行测试。 此外,请确保图像的大小不超过上述矩阵中提到的大小 您可以通过添加
console.log(file.size)
我正在使用最新版本的Chrome进行测试,文件大小为275088
.then(response => {
if (response) {
const file = new Blob([response.data], {type:'image/png'})
console.log(file.size) // !!! this line
return file
}