@cainiaofe/cn-utils
Version:
菜鸟前端基础工具库
63 lines (62 loc) • 1.82 kB
JavaScript
import { basename } from 'path-browserify';
import { isImage } from "../../common/type";
/**
* 下载图片
*/
var downloadImg = function (url, _fileName) {
var fileName = _fileName || basename(url);
var image = new Image();
image.setAttribute('crossOrigin', 'Anonymous');
image.onload = function () {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context === null || context === void 0 ? void 0 : context.drawImage(image, 0, 0, image.width, image.height);
var canvasUrl = canvas.toDataURL('images/png');
var a = document.createElement('a');
a.download = fileName;
a.href = canvasUrl;
a.click();
};
image.onerror = function () {
commonDownload(url, _fileName);
};
var tempUrl = new URL(url);
if (tempUrl.search) {
image.src = "".concat(url, "&v=").concat(Date.now());
}
else {
image.src = "".concat(url, "?v=").concat(Date.now());
}
};
/**
* 通用下载
*/
var commonDownload = function (fileUrl, _fileName) {
var fileName = _fileName || basename(fileUrl);
var a = document.createElement('a');
a.target = '_blank';
a.href = fileUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
/**
* 下载文件
* @param fileUrl 下载的文件路径
* @param fileName 重命名下载文件
*/
export var download = function (fileUrl, fileName) {
// 防护代码
if (!fileUrl)
return;
fileName = fileName || '';
if (isImage(fileUrl) || isImage(fileName)) {
downloadImg(fileUrl, fileName);
}
else {
commonDownload(fileUrl, fileName);
}
};