@sebgroup/frontend-tools
Version:
A set of frontend tools
57 lines (55 loc) • 1.99 kB
JavaScript
var FileType;
(function (FileType) {
FileType["JSON"] = "json";
FileType["PDF"] = "pdf";
FileType["SpreadSheet"] = "xlsx";
FileType["XML"] = "xml";
})(FileType || (FileType = {}));
function downloadFile(content, fileName, type) {
const blob = toBlob(content, type);
save(blob, fileName);
}
function toBlob(content, type) {
const byteArray = typeof content === "string" ? toByteArray(content) : [content];
return new Blob(byteArray, { type: toContentType(type) });
}
function toByteArray(base64Data, sliceSize = 512) {
const byteCharacters = window.atob(base64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
byteArrays.push(new Uint8Array(byteNumbers));
}
return byteArrays;
}
function toContentType(type) {
switch (type) {
case FileType.PDF:
return "application/pdf";
case FileType.SpreadSheet:
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case FileType.JSON:
return "application/json";
case FileType.XML:
return "text/xml";
default:
return "text/plain";
}
}
function save(blob, fileName) {
const url = window.URL.createObjectURL(blob);
const downloadableLink = document.createElement("a");
downloadableLink.download = fileName;
downloadableLink.href = url;
downloadableLink.style.display = "none";
document.body.appendChild(downloadableLink);
downloadableLink.click();
downloadableLink.remove();
window.URL.revokeObjectURL(url);
}
export { FileType, downloadFile };
//# sourceMappingURL=downloadFile.js.map