260914_01_ENH: 1차 완성
This commit is contained in:
51
src/lib/kmusical/file.ts
Normal file
51
src/lib/kmusical/file.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import {downloadFile} from "@kri/common/browser";
|
||||
|
||||
const trimDispositionValue = (value: string) => value.trim().replace(/^"|"$/g, "");
|
||||
|
||||
const decodeDispositionValue = (value: string) => {
|
||||
const trimmed = trimDispositionValue(value);
|
||||
const encodedValue = trimmed.includes("''") ? trimmed.split("''").slice(1).join("''") : trimmed;
|
||||
try {
|
||||
return decodeURIComponent(encodedValue);
|
||||
} catch {
|
||||
return encodedValue;
|
||||
}
|
||||
};
|
||||
|
||||
const getDispositionParams = (contentDisposition: string) =>
|
||||
contentDisposition
|
||||
.split(";")
|
||||
.slice(1)
|
||||
.map((part) => part.trim())
|
||||
.reduce<Record<string, string>>((params, part) => {
|
||||
const separatorIndex = part.indexOf("=");
|
||||
if (separatorIndex < 0) return params;
|
||||
const key = part.slice(0, separatorIndex).trim().toLowerCase();
|
||||
const value = part.slice(separatorIndex + 1).trim();
|
||||
if (key && value) params[key] = value;
|
||||
return params;
|
||||
}, {});
|
||||
|
||||
export const getFileNameFromContentDisposition = (contentDisposition?: string | null) => {
|
||||
if (!contentDisposition) return undefined;
|
||||
const params = getDispositionParams(contentDisposition);
|
||||
const fileName = params["filename*"] || params.filename;
|
||||
return fileName ? decodeDispositionValue(fileName) : undefined;
|
||||
};
|
||||
|
||||
export const downloadBlob = (buffer: ArrayBuffer, fileName: string, type = "application/octet-stream") => {
|
||||
downloadFile(new Blob([buffer], {type}), fileName);
|
||||
};
|
||||
|
||||
export const downloadExcelBuffer = (buffer: ArrayBuffer, fileName: string) => {
|
||||
downloadBlob(buffer, fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
};
|
||||
|
||||
export const downloadFromUrl = (url: string) => {
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
};
|
||||
Reference in New Issue
Block a user