PixelAI-admin/src/api/download/index.ts

37 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-12-16 13:41:43 +08:00
import axios from "axios";
2024-12-18 14:30:37 +08:00
import { ElMessage } from "element-plus";
2024-12-16 13:41:43 +08:00
const downloadPhoto = (imgSrc:any) => {
2024-12-27 15:03:48 +08:00
// 这个直接虚拟dom点击不然会有跨域问题
if(imgSrc.includes('guojunjie.oss-cn-hangzhou.aliyuncs.com')){
const a = document.createElement('a');
a.href = imgSrc;
a.download = '下载图片.'+ imgSrc.substr(imgSrc.lastIndexOf('.')+1) || 'jpg';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
ElMessage({message: '图片下载成功!',type: 'success',});
return;
}
2024-12-16 13:41:43 +08:00
axios({
url: imgSrc,
method: 'get',
headers: { 'Content-Type': 'application/json' },
responseType: 'blob',
}).then(res => {
const url = window.URL.createObjectURL(res.data);
const a = document.createElement('a');
a.href = url;
2024-12-26 20:16:59 +08:00
a.download = '下载图片.'+ imgSrc.substr(imgSrc.lastIndexOf('.')+1) || 'jpg';
2024-12-16 13:41:43 +08:00
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
2024-12-18 14:30:37 +08:00
ElMessage({message: '图片下载成功!',type: 'success',});
2024-12-16 13:41:43 +08:00
}).catch(error => {
2024-12-18 14:30:37 +08:00
ElMessage({message: '图片下载失败!',type: 'error',});
2024-12-16 13:41:43 +08:00
});
};
export { downloadPhoto };