Files
kmusical-manage-front/src/lib/kmusical/file.ts

69 lines
2.6 KiB
TypeScript

import {downloadFile} from "@kri/common/browser";
import {HttpError} from "@kri/common/http";
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");
};
/*
* 다운로드 API를 raw fetch로 호출해 Blob으로 저장한다.
* expectBinary 경로는 응답 헤더를 버리므로, 첨부파일 이름은 여기서 Content-Disposition으로 결정한다.
* 파일이 없으면 API가 404를 반환하며 HttpError로 전파한다.
*/
export const downloadFromApiUrl = async (url: string, fallbackFileName = "download") => {
const response = await fetch(url, {cache: "no-store"});
if (!response.ok) {
const data = await response.json().catch(() => null);
throw new HttpError(response.status, data, response.url, response.headers);
}
const blob = await response.blob();
const fileName = getFileNameFromContentDisposition(response.headers.get("content-disposition")) ?? fallbackFileName;
downloadFile(blob, fileName);
};
export const downloadFromUrl = (url: string) => {
const link = document.createElement("a");
link.href = url;
link.download = "";
document.body.appendChild(link);
link.click();
link.remove();
};