通过url下载文件或图片js
import request from '@/utils/request'
export function download(url) {
return request({
url: url,
method: 'get',
responseType: 'blob'
})
}
//模拟a标签实现下载excel文件
export function convert(blobUrl, filename) {
const a = document.createElement('a');
a.download = filename;
a.href = blobUrl;
a.click();
document.body.removeChild(a);
}
前提:前端连接的地址端口下有这个图片
response.msg 示例为 unzip/163/518/20240124-144926562000/7feb94adde1e45fcb634800744b4a38c.jpg
1、向服务器发送HTTP请求并获取响应。
要下载图片,必须创建GET请求并将图片的URL作为请求的URL
2、当请求成功后,需要将响应数据保存为图片文件
示例为下载pdf,更换其他类型文件注意更换blob的type
download(response.msg).then(resp => {
const blob = new Blob([resp], {
type: 'application/pdf;charset=utf-8'
})
// console.log(blob)
const url = URL.createObjectURL(blob)
convert(url, 'aa.pdf')
})