[英]how to prevent file upload when body validation fails in nestjs
在 nestjs 应用程序中上传文件之前,我要验证多部分表单。 问题是,如果正文验证失败,我不想上传文件。 这是我编写代码的方式。
// User controller method for create user with upload image
@Post()
@UseInterceptors(FileInterceptor('image'))
create(
@Body() userInput: CreateUserDto,
@UploadedFile(
new ParseFilePipe({
validators: [
// some validator here
]
})
) image: Express.Multer.File,
) {
return this.userService.create({ ...userInput, image: image.path });
}
尝试了很多方法来解决这个问题,但没有找到任何解决方案
拦截器在管道之前运行,因此除非您自己在服务中进行管理,否则无法保存文件。 但是,另一种选择可能是自定义异常过滤器,它会在错误时unlink
文件,这样您就不必担心上传后的问题
这就是我创建整个过滤器的方式
import { isArray } from 'lodash';
import {
ExceptionFilter,
Catch,
ArgumentsHost,
BadRequestException,
} from '@nestjs/common';
import { Request, Response } from 'express';
import * as fs from 'fs';
@Catch(BadRequestException)
export class DeleteFileOnErrorFilter implements ExceptionFilter {
catch(exception: BadRequestException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
const getFiles = (files: Express.Multer.File[] | unknown | undefined) => {
if (!files) return [];
if (isArray(files)) return files;
return Object.values(files);
};
const filePaths = getFiles(request.files);
for (const file of filePaths) {
fs.unlink(file.path, (err) => {
if (err) {
console.error(err);
return err;
}
});
}
response.status(status).json(exception.getResponse());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.