const { bufferedFiles } = Sonamu.getContext();const file = bufferedFiles?.[0]; // 첫 번째 파일 사용const buffer = file.buffer;console.log(buffer instanceof Buffer); // trueconsole.log(buffer.length); // 파일 크기 (바이트)
md5()
파일의 MD5 해시를 계산합니다.
const { bufferedFiles } = Sonamu.getContext();const file = bufferedFiles?.[0]; // 첫 번째 파일 사용const hash = await file.md5();console.log(hash); // '5d41402abc4b2a76b9719d911017c592'
용도:
파일 중복 체크
파일 무결성 검증
고유한 파일명 생성
saveToDisk(diskName, key)
파일을 디스크에 저장합니다.
const { bufferedFiles } = Sonamu.getContext();const file = bufferedFiles?.[0]; // 첫 번째 파일 사용// fs 디스크에 저장const url = await file.saveToDisk("fs", "uploads/file.pdf");// 특정 디스크에 저장const url = await file.saveToDisk("s3", "uploads/file.pdf");
반환값: 저장된 파일의 URL (unsigned)
실전 예제
1. 프로필 사진 업로드
class UserModelClass extends BaseModelClass { @upload() async uploadAvatar(ctx: Context) { const { bufferedFiles } = Sonamu.getContext(); const file = bufferedFiles?.[0]; // 첫 번째 파일 사용 if (!file) { throw new Error("파일이 없습니다"); } // 이미지 파일만 허용 if (!file.mimetype.startsWith("image/")) { throw new Error("이미지 파일만 업로드 가능합니다"); } // 파일 크기 제한 (5MB) const maxSize = 5 * 1024 * 1024; // 5MB if (file.size > maxSize) { throw new Error("파일 크기는 5MB 이하여야 합니다"); } // 파일명: user-{id}-{timestamp}.{ext} const timestamp = Date.now(); const ext = file.extname || "png"; const key = `avatars/user-${ctx.user.id}-${timestamp}.${ext}`; // 저장 const url = await file.saveToDisk("fs", key); // DB 업데이트 await this.getPuri("w").table("users").where("id", ctx.user.id).update({ avatar_url: url, updated_at: new Date(), }); return { url }; }}
2. 다중 이미지 업로드
class PostModelClass extends BaseModelClass { @upload() async uploadImages(postId: number, ctx: Context) { const { bufferedFiles } = Sonamu.getContext(); // 파일 개수 제한 if ((bufferedFiles?.length ?? 0) > 10) { throw new Error("최대 10개까지 업로드 가능합니다"); } // 이미지만 필터링 const imageFiles = (bufferedFiles ?? []).filter((file) => file.mimetype.startsWith("image/")); if (imageFiles.length === 0) { throw new Error("이미지 파일이 없습니다"); } // 모든 이미지 저장 const urls = await Promise.all( imageFiles.map(async (file, index) => { const timestamp = Date.now(); const ext = file.extname || "png"; const key = `posts/${postId}/image-${index}-${timestamp}.${ext}`; return await file.saveToDisk("fs", key); }), ); return { urls, count: urls.length }; }}
3. 파일 타입별 검증
class FileModelClass extends BaseModelClass { @upload() async uploadDocument(type: "pdf" | "excel" | "word") { const { bufferedFiles } = Sonamu.getContext(); const file = bufferedFiles?.[0]; // 첫 번째 파일 사용 if (!file) { throw new Error("파일이 없습니다"); } // MIME 타입 검증 const allowedMimeTypes = { pdf: ["application/pdf"], excel: [ "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ], word: [ "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ], }; if (!allowedMimeTypes[type].includes(file.mimetype)) { throw new Error(`${type} 파일만 업로드 가능합니다`); } // 파일 저장 const key = `documents/${type}/${Date.now()}-${file.filename}`; const url = await file.saveToDisk("fs", key); return { url, type, filename: file.filename }; }}
4. MD5 해시로 중복 체크
class MediaModelClass extends BaseModelClass { @upload() async uploadMedia() { const { bufferedFiles } = Sonamu.getContext(); const file = bufferedFiles?.[0]; // 첫 번째 파일 사용 if (!file) { throw new Error("파일이 없습니다"); } // MD5 해시 계산 const hash = await file.md5(); // 이미 존재하는 파일인지 확인 const existing = await this.findOne("A", { sonamuFilter: { md5_hash: hash } }); if (existing) { // 이미 존재하면 기존 URL 반환 return { url: existing.url, duplicate: true, }; } // 새 파일 저장 const key = `media/${hash}.${file.extname}`; const url = await file.saveToDisk("fs", key); // DB에 저장 await this.save([{ md5_hash: hash, url, filename: file.filename, size: file.size, mimetype: file.mimetype, }]); return { url, duplicate: false }; }}
5. 디스크 선택
class FileModelClass extends BaseModelClass { @upload() async upload(visibility: "public" | "private", ctx: Context) { const { bufferedFiles } = Sonamu.getContext(); const file = bufferedFiles?.[0]; // 첫 번째 파일 사용 if (!file) { throw new Error("파일이 없습니다"); } // visibility에 따라 다른 디스크 사용 const diskName = visibility === "public" ? "public" : "fs"; const key = `${visibility}/${ctx.user.id}/${Date.now()}-${file.filename}`; // 저장 const url = await file.saveToDisk(diskName, key); // DB에 저장 await this.save([{ user_id: ctx.user.id, url, visibility, filename: file.filename, }]); return { url, visibility }; }}
파일 조회
Storage Manager를 사용하여 저장된 파일을 조회합니다.
파일 읽기
import { Sonamu } from "sonamu";@api({ httpMethod: 'GET' })async getFile(key: string) { const disk = Sonamu.storage.use(); // 파일 존재 확인 const exists = await disk.exists(key); if (!exists) { throw new Error('파일이 없습니다'); } // 파일 읽기 const content = await disk.get(key); return content; // Buffer}
파일 다운로드 API
@api({ httpMethod: 'GET', contentType: 'application/octet-stream',})async downloadFile(key: string, ctx: Context) { const disk = Sonamu.storage.use(); // 파일 존재 확인 const exists = await disk.exists(key); if (!exists) { throw new Error('파일이 없습니다'); } // 파일 읽기 const buffer = await disk.get(key); // 파일명 추출 const filename = key.split('/').pop() || 'download'; // 다운로드 헤더 설정 ctx.reply.header('Content-Disposition', `attachment; filename="${filename}"`); return buffer;}
URL 가져오기
@api({ httpMethod: 'GET' })async getFileUrl(key: string) { const disk = Sonamu.storage.use(); // 파일 존재 확인 const exists = await disk.exists(key); if (!exists) { throw new Error('파일이 없습니다'); } // URL 가져오기 const url = await disk.getUrl(key); return { url };}