const { bufferedFiles } = Sonamu.getContext();const file = bufferedFiles?.[0]; // Use first fileconst hash = await file.md5();console.log(hash); // '5d41402abc4b2a76b9719d911017c592'
Use cases:
File deduplication check
File integrity verification
Unique filename generation
saveToDisk(diskName, key)
Saves the file to disk.
const { bufferedFiles } = Sonamu.getContext();const file = bufferedFiles?.[0]; // Use first file// Save to fs diskconst url = await file.saveToDisk("fs", "uploads/file.pdf");// Save to specific diskconst url = await file.saveToDisk("s3", "uploads/file.pdf");
Return value: URL of the saved file (unsigned)
Practical Examples
1. Profile Photo Upload
class UserModelClass extends BaseModelClass { @upload() async uploadAvatar(ctx: Context) { const { bufferedFiles } = Sonamu.getContext(); const file = bufferedFiles?.[0]; // Use first file if (!file) { throw new Error("No file provided"); } // Allow only image files if (!file.mimetype.startsWith("image/")) { throw new Error("Only image files can be uploaded"); } // File size limit (5MB) const maxSize = 5 * 1024 * 1024; // 5MB if (file.size > maxSize) { throw new Error("File size must be 5MB or less"); } // Filename: user-{id}-{timestamp}.{ext} const timestamp = Date.now(); const ext = file.extname || "png"; const key = `avatars/user-${ctx.user.id}-${timestamp}.${ext}`; // Save const url = await file.saveToDisk("fs", key); // Update DB await this.getPuri("w").table("users").where("id", ctx.user.id).update({ avatar_url: url, updated_at: new Date(), }); return { url }; }}
2. Multiple Image Upload
class PostModelClass extends BaseModelClass { @upload() async uploadImages(postId: number, ctx: Context) { const { bufferedFiles } = Sonamu.getContext(); // Limit number of files if ((bufferedFiles?.length ?? 0) > 10) { throw new Error("Maximum 10 files can be uploaded"); } // Filter images only const imageFiles = (bufferedFiles ?? []).filter((file) => file.mimetype.startsWith("image/")); if (imageFiles.length === 0) { throw new Error("No image files found"); } // Save all images 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. File Type Validation
class FileModelClass extends BaseModelClass { @upload() async uploadDocument(type: "pdf" | "excel" | "word") { const { bufferedFiles } = Sonamu.getContext(); const file = bufferedFiles?.[0]; // Use first file if (!file) { throw new Error("No file provided"); } // MIME type validation 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(`Only ${type} files can be uploaded`); } // Save file const key = `documents/${type}/${Date.now()}-${file.filename}`; const url = await file.saveToDisk("fs", key); return { url, type, filename: file.filename }; }}
4. Deduplication Check with MD5 Hash
class MediaModelClass extends BaseModelClass { @upload() @api({ httpMethod: "POST" }) async uploadMedia() { const { files } = Sonamu.getContext(); const file = files?.[0]; // Use first file if (!file) { throw new Error("No file provided"); } // Calculate MD5 hash const hash = await file.md5(); // Check if file already exists const existing = await this.findOne("A", { sonamuFilter: { md5_hash: hash } }); if (existing) { // Return existing URL if already exists return { url: existing.url, duplicate: true, }; } // Save new file const key = `media/${hash}.${file.extname}`; const url = await file.saveToDisk("fs", key); // Save to DB await this.save([{ md5_hash: hash, url, filename: file.filename, size: file.size, mimetype: file.mimetype, }]); return { url, duplicate: false }; }}
5. Disk Selection
class FileModelClass extends BaseModelClass { @upload() @api({ httpMethod: "POST" }) async upload(visibility: "public" | "private", ctx: Context) { const { files } = Sonamu.getContext(); const file = files?.[0]; // Use first file if (!file) { throw new Error("No file provided"); } // Use different disk based on visibility const disk = visibility === "public" ? "public" : "private"; const key = `${visibility}/${ctx.user.id}/${Date.now()}-${file.filename}`; // Save const url = await file.saveToDisk(disk, key); // Save to DB await this.save([{ user_id: ctx.user.id, url, visibility, filename: file.filename, }]); return { url, visibility }; }}
File Retrieval
Use Storage Manager to retrieve saved files.
Reading Files
import { Sonamu } from "sonamu";@api({ httpMethod: 'GET' })async getFile(key: string) { const disk = Sonamu.storage.use(); // Check file existence const exists = await disk.exists(key); if (!exists) { throw new Error('File not found'); } // Read file const content = await disk.get(key); return content; // Buffer}
File Download API
@api({ httpMethod: 'GET', contentType: 'application/octet-stream',})async downloadFile(key: string, ctx: Context) { const disk = Sonamu.storage.use(); // Check file existence const exists = await disk.exists(key); if (!exists) { throw new Error('File not found'); } // Read file const buffer = await disk.get(key); // Extract filename const filename = key.split('/').pop() || 'download'; // Set download headers ctx.reply.header('Content-Disposition', `attachment; filename="${filename}"`); return buffer;}
Getting URL
@api({ httpMethod: 'GET' })async getFileUrl(key: string) { const disk = Sonamu.storage.use(); // Check file existence const exists = await disk.exists(key); if (!exists) { throw new Error('File not found'); } // Get URL const url = await disk.getUrl(key); return { url };}
const maxSize = 10 * 1024 * 1024; // 10MBif (file.size > maxSize) { throw new Error("File is too large");}
MIME type validation: Donβt trust only the extension
// β Only checking extensionif (file.filename.endsWith('.png')) { ... }// β Check MIME typeif (file.mimetype === 'image/png') { ... }// mimetype is also sent by the client; check the file signature when the contents matter