同源图片下载

html中可以这样写

1
<a href="./img/logo.png" download="logo.png"></a>

javascript中可以这样写

1
2
3
4
5
6
7
8
9
10
function imgDownload(url,name){
//创建一个a标签
const a_b = document.createElement('a');
//设置href指向
a_b.href = url;
//设置图片下载名字
a_b.download = name;
//点击a标签
a_b.click()
}

非同源图片下载方案

通过axios请求来实现图片下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function downloadByAxios(url,name){
axios({
//设置图片路径
url:url,
//设置请求方法为get请求
method:'get',
//设置相应类型为blob
responseType: 'blob'
}).then(
//得到的是一个blob对象
res => {
let url = window.URL.createObjectURL(res.data)
const a = document.createElement('a');
a.href = url
a.download = name
a.click()
}
)
}