如果你从api获取了一个图片的url,使用 <img> 标签可以轻易的将其展示在页面上,但是你并不需要展示它,而是要下载它,怎么办?
下面给出三种解决办法:
使用 fetch:
export const downloadImage = (imageUrl: string, name: string): void => {
fetch(imageUrl, {
method: 'get',
mode: 'cors',
})
.then((response) => response.blob())
.then((data) => {
const downloadUrl = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', name);
document.body.appendChild(link);
link.click();
link.remove();
});
};
使用 axios:
export const downloadImage = (imageUrl: string, name: string): void => {
axios.get(imageUrl, {responseType: 'blob'}).then((res) => {
const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', name);
document.body.appendChild(link);
link.click();
link.remove();
});
};
使用 canvas:
export const downloadImage = (imageUrl: string, name: string): void => {
const image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function (): void {
console.log(image);
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d') as CanvasRenderingContext2D;
context.drawImage(image, 0, 0, image.width, image.height);
const url = canvas.toDataURL('image/png');
const a = document.createElement('a');
const event = new MouseEvent('click');
a.download = name;
a.href = url;
a.dispatchEvent(event);
};
image.src = imageUrl;
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。