Skip to content

Commit

Permalink
feat: 파일 다운로드 유틸함수 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
hynseok committed Aug 31, 2024
1 parent 04c7dc0 commit 602ae9b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/utils/handleDownloadFile/handleDownloadFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { CommonAxios } from "../CommonAxios";

type TArg = {
fileId: number;
fileName: string;
};

// 파일의 ID와 파일명이 있을 때 다운로드 하는 함수
export async function handleDownloadFile({ fileId, fileName }: TArg) {
const url = await getFileUrlById(fileId);
const a = document.createElement("a");

a.href = url;
a.download = fileName;
a.click();

URL.revokeObjectURL(url);
}

// 파일의 ID가 있을 때 파일의 URL을 가져오는 함수 (next Image src 등에서 사용)
export async function getFileUrlById(fileId: number) {
const result = await CommonAxios({
url: `/files/${fileId}`,
responseType: "blob",
});

const blob = new Blob([result.data]);

const url = URL.createObjectURL(blob);

return url;
}
2 changes: 2 additions & 0 deletions src/utils/handleDownloadFile/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { handleDownloadFile } from "./handleDownloadFile";
export { getFileUrlById } from "./handleDownloadFile";

0 comments on commit 602ae9b

Please sign in to comment.