@iimm/shared
Version:
shared utils on browser and react env
62 lines • 2.58 kB
JavaScript
import { getFileNameFromUrl } from "../../url";
/** 将传入的file下载 */
export var generateFileDownload = function generateFileDownload(file) {
var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
var extension = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
var options = arguments.length > 3 ? arguments[3] : undefined;
var _ref = options || {},
onDownloadFail = _ref.onDownloadFail,
onDownloadStart = _ref.onDownloadStart,
onDownloadSuccess = _ref.onDownloadSuccess,
_ref$maxFileNameLengt = _ref.maxFileNameLength,
maxFileNameLength = _ref$maxFileNameLengt === void 0 ? 50 : _ref$maxFileNameLengt;
if (!file) return;
var href = "";
var needClear = false;
var fileName = name;
try {
if (typeof file === "string") {
href = file;
if (!fileName) {
fileName = getFileNameFromUrl(href);
}
} 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) {
var _fileName;
if (start === false) {
if (needClear) {
URL.revokeObjectURL(href);
}
return;
}
var a = document.createElement("a");
a.href = href;
a.download = fileName ? ((_fileName = fileName) === null || _fileName === void 0 ? void 0 : _fileName.length) > maxFileNameLength ? fileName.slice(-1 * maxFileNameLength) : 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 || onDownloadSuccess(file, fileName);
} else {
throw new Error("文件无法识别");
}
} catch (error) {
console.log("downloadFileError", error);
onDownloadFail === null || onDownloadFail === void 0 || onDownloadFail(file, fileName);
}
};