diginext-utils
Version:
README.md
74 lines (73 loc) • 2.82 kB
JavaScript
import { saveAs } from "file-saver";
import { isMobile } from "../device/index";
import { randomFileName } from "../string/random";
import { getExtensionFromMimeType } from "../string/url";
export const doGetFile = async (url, data) => {
const response = await fetch(url);
if (!response.ok) {
return undefined;
}
const blob = await response.blob();
const ext = getExtensionFromMimeType(blob.type);
const filename = (data === null || data === void 0 ? void 0 : data.filename) ? `${data === null || data === void 0 ? void 0 : data.filename}.${ext}` : `${randomFileName("img", 3)}.${ext}`;
const file = new File([blob], filename, {
type: blob.type,
});
return { file, filename };
};
export const doSaveFileDesktop = async (url, data) => {
//
if (!(data === null || data === void 0 ? void 0 : data.file)) {
const __data = await doGetFile(url, data);
const file = __data === null || __data === void 0 ? void 0 : __data.file;
const filename = __data === null || __data === void 0 ? void 0 : __data.filename;
if (!file || !filename)
return false;
try {
saveAs(file, filename);
}
catch (error) {
window.open(url, "_self");
console.error(`saveWhenError error`, error);
}
}
return true;
};
export const doSaveFileMobile = async (url, data) => {
return new Promise(async (resolve, reject) => {
const __data = await doGetFile(url, data);
const file = __data === null || __data === void 0 ? void 0 : __data.file;
const filename = __data === null || __data === void 0 ? void 0 : __data.filename;
if (!file || !filename)
return false;
navigator
.share({
files: [file],
title: filename,
})
.then(() => {
resolve(true);
// alert(0);
// console.log(0);
})
.catch(async (err) => {
var _a, _b, _c, _d;
if ((_b = (_a = `${err}`).includes) === null || _b === void 0 ? void 0 : _b.call(_a, "AbortError"))
return;
if ((_d = (_c = err === null || err === void 0 ? void 0 : err.message) === null || _c === void 0 ? void 0 : _c.includes) === null || _d === void 0 ? void 0 : _d.call(_c, "cancellation"))
return;
console.error(`navigator error`, err);
await doSaveFileDesktop(url, data);
resolve(true);
});
});
};
export default async function downloadByUrl(url, data) {
//
if (isMobile()) {
return doSaveFileMobile(url, data);
}
else {
return doSaveFileDesktop(url, data);
}
}