@iimm/shared
Version:
shared utils on browser and react env
60 lines • 2.29 kB
JavaScript
/** 将传入的file下载 */
export var generateFileDownload = function generateFileDownload(file) {
var fileName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var extension = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
var callbacks = arguments.length > 3 ? arguments[3] : undefined;
var _ref = callbacks || {},
onDownloadFail = _ref.onDownloadFail,
onDownloadStart = _ref.onDownloadStart,
onDownloadSuccess = _ref.onDownloadSuccess;
if (!file) return;
var href = '';
var needClear = false;
try {
if (typeof file === 'string') {
href = file;
if (!fileName) {
var last = file.lastIndexOf('/');
if (last !== -1) {
fileName = file.slice(last + 1);
}
}
} else if (file instanceof ArrayBuffer) {
href = URL.createObjectURL(new Blob([file]));
needClear = true;
} else if (file instanceof File || file instanceof Blob) {
if (!fileName && file instanceof File && file.name) {
fileName = file.name;
}
href = URL.createObjectURL(file);
needClear = true;
}
if (fileName && extension && !fileName.includes('.')) {
fileName = "".concat(fileName, ".").concat(extension.startsWith('.') ? extension.slice(1) : extension);
}
var start = onDownloadStart === null || onDownloadStart === void 0 ? void 0 : onDownloadStart(file, fileName);
if (href) {
if (start === false) {
if (needClear) {
URL.revokeObjectURL(href);
}
return;
}
var a = document.createElement('a');
a.href = href;
a.download = fileName || "\u6587\u4EF6.".concat(extension ? extension.startsWith('.') ? extension.slice(1) : extension : '请修改扩展名');
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
if (needClear) {
URL.revokeObjectURL(href);
}
onDownloadSuccess === null || onDownloadSuccess === void 0 ? void 0 : onDownloadSuccess(file, fileName);
} else {
throw new Error('文件无法识别');
}
} catch (error) {
console.log('downloadFileError', error);
onDownloadFail === null || onDownloadFail === void 0 ? void 0 : onDownloadFail(file, fileName);
}
};