Files
sam-react-prod/src/lib/utils/fileDownload.ts

62 lines
1.7 KiB
TypeScript
Raw Normal View History

/**
*
*
* API: GET /api/v1/files/{id}/download
* 프록시: GET /api/proxy/files/{id}/download
*/
import { downloadBlob } from './export';
/**
* Content-Disposition
*/
function extractFilenameFromHeader(response: Response): string | null {
const contentDisposition = response.headers.get('Content-Disposition');
if (!contentDisposition) return null;
const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if (!match?.[1]) return null;
const raw = match[1].replace(/['"]/g, '');
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
}
/**
* ID로
* @param fileId ID
* @param fileName (, )
*/
export async function downloadFileById(fileId: number, fileName?: string): Promise<void> {
try {
const response = await fetch(`/api/proxy/files/${fileId}/download`);
if (!response.ok) {
throw new Error(`다운로드 실패: ${response.status}`);
}
const blob = await response.blob();
const downloadFileName = fileName
?? extractFilenameFromHeader(response)
?? `file_${fileId}`;
downloadBlob(blob, downloadFileName);
} catch (error) {
console.error('[fileDownload] 다운로드 오류:', error);
throw error;
}
}
/**
* ()
* @param filePath
*/
export function openFileInNewTab(filePath: string): void {
// 백엔드 파일 서빙 URL 구성
const baseUrl = process.env.NEXT_PUBLIC_API_URL || '';
const fileUrl = `${baseUrl}/storage/${filePath}`;
window.open(fileUrl, '_blank');
}