Tiếp tục với series, sau Bài 21 mỗi user chỉ thao tác được trên project và task của mình. Bài này mình sẽ giới thiệu với mọi người về upload file trong NestJS để đính kèm ảnh chụp màn hình, file PDF cho task.
1. Upload file trong NestJS.
File được gửi bằng body dạng multipart/form-data mà body parser JSON không đọc được. NestJS dùng multer (2.5.0, có sẵn trong @nestjs/platform-express) qua các interceptor:
FileInterceptor('file'): nhận một file ở fieldfile, lấy ra bằng@UploadedFile().FilesInterceptor('files', 5): nhận tối đa 5 file cùng fieldfiles, lấy ra bằng@UploadedFiles()(mảng).
Mặc định multer giữ file trong RAM (file.buffer) và không giới hạn kích thước. Kiểu Express.Multer.File nằm ở @types/multer (2.3.0), cài xong thêm "multer" vào mảng "types" của tsconfig.json:
npm install -D @types/multer
2. Bảng attachments.
Trong prisma/schema.prisma, thêm model Attachment (@@map("attachments")) gồm id, taskId (quan hệ tới Task, onDelete: Cascade), storedName String @unique (tên file trên đĩa), originalName String @db.VarChar(255), mimeType, size Int, createdAt; model Task thêm attachments Attachment[]. Sau đó tạo bảng và module:
npx prisma migrate dev --name attachments
npx prisma generate
nest g module attachments --format
nest g service attachments --no-spec --format
nest g controller attachments --no-spec --format
AttachmentsModule thêm exports: [AttachmentsService]. Controller đổi thành @Controller('tasks/:taskId/attachments'): upload, liệt kê, tải về và xoá file của một task.
3. Nhận và kiểm tra file.
- src/attachments/attachments.controller.ts (đoạn trích, các validator và ParseFilePipe import từ @nestjs/common, FilesInterceptor từ @nestjs/platform-express)
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB
const MAX_FILES = 5;
@Controller('tasks/:taskId/attachments')
export class AttachmentsController {
constructor(private readonly attachmentsService: AttachmentsService) {}
@Post()
@UseInterceptors(
FilesInterceptor('files', MAX_FILES, {
// Multer dừng nhận ngay khi vượt giới hạn
limits: { fileSize: MAX_FILE_SIZE, files: MAX_FILES, fields: 0 },
defParamCharset: 'utf8', // tên file có dấu tiếng Việt
}),
)
upload(
@Param('taskId', ParseIdPipe) taskId: number,
@UploadedFiles(
new ParseFilePipe({
validators: [
new MaxFileSizeValidator({ maxSize: MAX_FILE_SIZE }),
// Kiểm tra magic number, ghi đè mimetype client gửi
new FileTypeValidator({
fileType: /^(image\/(png|jpeg|webp)|application\/pdf)$/,
overrideMimeType: true,
}),
],
}),
)
files: Express.Multer.File[],
@CurrentUser() user: AuthUser,
): Promise<AttachmentInfo[]> {
return this.attachmentsService.upload(taskId, files, user.id);
}
Trong đó:
limitschặn ngay trong lúc nhận: file quá 5 MB trả 413File too largemà không nằm hết trong RAM; quá 5 file trả 400Too many files;fields: 0từ chối mọi field text (400Too many fields).- Multer mặc định đọc tên file theo latin1, tên tiếng Việt sẽ lỗi font nếu không đặt
defParamCharset: 'utf8'. ParseFilePipechạy các validator với từng file, sai thì trả 400, không có file thì trảFile is required.MaxFileSizeValidatorchạy khi đã nhận xong file nên chỉ là lớp kiểm tra thứ hai.FileTypeValidatorkhông tinContent-Typeclient gửi mà đọc magic number (vài byte đầu file) bằng packagefile-type;overrideMimeType: truelưu lại kiểu đọc được.
Lưu ý: Magic number cần file.buffer nên chỉ chạy với memory storage. Nó không nhận ra file văn bản (txt, csv, svg) và chỉ xem phần đầu file: một file PNG nối thêm mã HTML vẫn qua. Vì vậy file tải về luôn là attachment, không bao giờ hiển thị thẳng trên trình duyệt.
4. Lưu file an toàn.
- src/attachments/attachments.service.ts (đoạn trích)
// Không trả storedName cho client
const attachmentSelect = {
id: true,
taskId: true,
originalName: true,
mimeType: true,
size: true,
createdAt: true,
} satisfies Prisma.AttachmentSelect;
export type AttachmentInfo = Prisma.AttachmentGetPayload<{
select: typeof attachmentSelect;
}>;
// ... trong class AttachmentsService:
async upload(
taskId: number,
files: Express.Multer.File[],
userId: number,
): Promise<AttachmentInfo[]> {
await this.checkTask(taskId, userId);
await mkdir(UPLOAD_DIR, { recursive: true });
const rows: Prisma.AttachmentCreateManyInput[] = [];
try {
for (const file of files) {
// Tên trên đĩa là UUID ngẫu nhiên, không dùng tên client gửi
const storedName = randomUUID();
await writeFile(join(UPLOAD_DIR, storedName), file.buffer, {
flag: 'wx', // không bao giờ ghi đè file có sẵn
});
rows.push({
taskId,
storedName,
originalName: cleanName(file.originalname),
mimeType: file.mimetype, // đã đổi theo magic number
size: file.size,
});
}
return await this.prisma.attachment.createManyAndReturn({
data: rows,
select: attachmentSelect,
});
} catch (error) {
// Lưu database lỗi: xoá các file vừa ghi
await this.removeFiles(rows.map((row) => row.storedName));
throw error;
}
}
Trong đó:
attachmentSelectchọn các cột trả cho client, cố ý bỏstoredName(tên file trên đĩa);AttachmentInfolà kiểu suy ra từ nó.UPLOAD_DIRlàjoin(process.cwd(), 'storage', 'attachments'), nằm ngoài mọi thư mục public nên chỉ tải được qua route có kiểm tra quyền; thêm/storagevào.gitignore.- Tên client gửi có thể là
../../etc/passwdnên chỉ lưu vàooriginalNamesau khicleanName()bỏ ký tự điều khiển,/,\. checkTask()dùng lại điều kiện sở hữu của Bài 21 (task.count({ where: { id: taskId, project: { ownerId: userId } } })), không khớp thì trả 404Không tìm thấy task N.
5. Tải file về và xoá file.
download() tìm file bằng findUnique({ where: { id, taskId, task: { project: { ownerId: userId } } } }), không thấy thì trả 404, rồi trả về StreamableFile để stream file thay vì đọc cả file vào RAM:
const path = join(UPLOAD_DIR, attachment.storedName);
return new StreamableFile(createReadStream(path), {
type: attachment.mimeType,
length: attachment.size,
disposition: contentDisposition(attachment.originalName),
});
Tên file trong header Content-Disposition phải được làm sạch để dấu " không phá header:
// filename="..." chỉ giữ ASCII an toàn, tên UTF-8 đầy đủ nằm ở filename*
function contentDisposition(name: string): string {
const ascii = name.replace(/[^\x20-\x7e]|["\\%]/g, '_');
const utf8 = encodeURIComponent(name).replace(
/['()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
return `attachment; filename="${ascii}"; filename*=UTF-8''${utf8}`;
}
Route @Get(':id') gắn @SkipTransform() (Bài 13) để file không bị bọc trong { data } và @Header('X-Content-Type-Options', 'nosniff') để trình duyệt không tự đoán kiểu file. remove() xoá bản ghi với cùng điều kiện sở hữu (không khớp là P2025, 404) rồi xoá file bằng rm(path, { force: true }).
onDelete: Cascade chỉ xoá bản ghi, file vẫn nằm trên đĩa. TasksService và ProjectsService inject AttachmentsService (thêm AttachmentsModule vào imports của hai module, projects.*.spec.ts thêm { provide: AttachmentsService, useValue: {} }). Trong remove(), lấy tên file trước bằng await this.attachments.storedNames({ taskId: id }) (project: { task: { projectId: id } }, khi không có moveTasksTo), xoá bản ghi thành công rồi mới gọi await this.attachments.removeFiles(files).
6. Thử upload với curl.
Reset dữ liệu như Bài 21, tạo task 1 trong project 1 bằng token của tai ($A), An ($B) là user thứ hai:
curl http://localhost:3000/api/v1/tasks/1/attachments -H "$A" \
-F "[email protected]" -F "files=@Báo cáo tháng 11.pdf;type=text/plain"
# {"data":[{"id":1,"taskId":1,"originalName":"anh-chup.png","mimeType":"image/png","size":67,...},
# {"id":2,"taskId":1,"originalName":"Báo cáo tháng 11.pdf","mimeType":"application/pdf","size":45,...}]}
echo '<script>alert(1)</script>' > hack.png
curl http://localhost:3000/api/v1/tasks/1/attachments -H "$A" -F "[email protected];type=image/png"
# {"statusCode":400,"errorCode":"BAD_REQUEST","message":"Validation failed (file type could not be detected from its content; ...)",...}
curl -D - -o bao-cao.pdf http://localhost:3000/api/v1/tasks/1/attachments/2 -H "$A"
# HTTP/1.1 200 OK
# X-Content-Type-Options: nosniff
# Content-Type: application/pdf
# Content-Disposition: attachment; filename="B_o c_o th_ng 11.pdf"; filename*=UTF-8''B%C3%A1o%20c%C3%A1o%20th%C3%A1ng%2011.pdf
# Content-Length: 45
curl http://localhost:3000/api/v1/tasks/1/attachments/2 -H "$B"
# {"statusCode":404,"errorCode":"NOT_FOUND","message":"Không tìm thấy file 2",...}
curl -X DELETE http://localhost:3000/api/v1/tasks/1 -H "$A"
ls storage/attachments
# (trống: file của task 1 đã bị xoá)
Khi chạy nhiều server, hãy thay thư mục storage bằng dịch vụ như S3, cách kiểm tra quyền và đặt tên file giữ nguyên. Ở production nên giới hạn thêm tổng dung lượng file của mỗi user (cộng size trước khi ghi) và kích thước body ở reverse proxy.
7. Lời kết.
Như vậy mình đã giới thiệu với mọi người về upload file trong NestJS: giới hạn của multer, ParseFilePipe kiểm tra kích thước, kiểu file, lưu file bằng tên ngẫu nhiên, tải về an toàn và dọn file khi xoá. API đã khá nhiều route, bài sau mình sẽ giới thiệu về tài liệu API với Swagger trong NestJS.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments