diff options
Diffstat (limited to 'lib/storage.ts')
| -rw-r--r-- | lib/storage.ts | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/lib/storage.ts b/lib/storage.ts new file mode 100644 index 00000000..ead937aa --- /dev/null +++ b/lib/storage.ts @@ -0,0 +1,44 @@ +import fs from "fs/promises" +import path from "path" +import crypto from "crypto" + +/** + * 주어진 File을 해시된 파일명으로 로컬에 저장하고, + * 저장된 파일의 메타데이터를 반환하는 공용 함수 + */ +export async function saveDocument( + file: File, + directory: string = "./public" +) { + // 확장자 추출 + const originalName = file.name + const ext = path.extname(originalName) || "" + + // 해시 파일명 생성 + const randomHash = crypto.randomBytes(20).toString("hex") + const hashedFileName = randomHash + ext + + // 파일 저장 + await storeFile(file, hashedFileName, directory) + + // 필요한 메타데이터 반환 (원본 이름, 해시 파일명 등) + return { + originalName, + hashedFileName, + ext, + // 필요하면 file.size, file.type 등도 포함 가능 + } +} + +/** + * 실제 파일 쓰기 (로컬이든, S3든 자유롭게 교체 가능) + */ +async function storeFile(file: File, hashedFileName: string, directory: string) { + const arrayBuffer = await file.arrayBuffer() + const buffer = Buffer.from(arrayBuffer) + + const filePath = path.join(directory, hashedFileName) + + // 만약 기존 파일에 추가가 아니라 새 파일 생성이라면 writeFile 사용 + await fs.writeFile(filePath, buffer) +}
\ No newline at end of file |
