我试图使用内置的multer上传文件,然后将响应发送回给用户以获取成功或失败。直到今天,一切都很顺利,直到我尝试上传回应时才来。经过一番挖掘后,我发现当我将@res与@UploadedFile一起使用时,它不会执行控制器。我是nest.js的新手。
工作。
@Post('uploads/avatar')
async uploadFile(@Req() req, @UploadedFile() avatar) {
console.log(req.body);
if (!req.body.user_id) {
throw new Error('id params not found.');
}
try {
const resultUpload = await this.userService.uploadUserImage(
req.body.user_id,
avatar,
); // returns the url for the uploaded image
return resultUpload;
} catch (error) {
console.log(error);
return error;
}
}
不起作用。
@Post('uploads/avatar')
async uploadFile(@Req() req, @UploadedFile() avatar, @Res() res) {
console.log(req.body);
if (!req.body.user_id) {
throw new Error('id params not found.');
}
try {
const resultUpload = await this.userService.uploadUserImage(
req.body.user_id,
avatar,
); // returns the url for the uploaded image
return resultUpload;
res.send(resultUpload);
} catch (error) {
console.log(error);
res.send(error);
}
}
答案 0 :(得分:1)
在嵌套中,您应始终避免注入@Res
,因为这样会丢失很多使嵌套如此强大的东西:拦截器,异常过滤器......
实际上,在大多数情况下,您不需要@Res
,因为nest会自动处理正确的响应。
如果要从控制器方法发送数据,则只需返回数据(Promises
和Observables
也会自动解析)。如果您想将错误发送给客户端,则只需抛出相应的HttpException
,例如404-> NotFoundException
:
@Post('uploads/avatar')
async uploadFile(@Req() req, @UploadedFile() avatar) {
if (!req.body.user_id) {
// throw a 400
throw new BadRequestException('id params not found.');
}
try {
const resultUpload = await this.userService.uploadUserImage(
req.body.user_id,
avatar,
);
return resultUpload;
} catch (error) {
if (error.code === 'image_already_exists') {
// throw a 409
throw new ConflictException('image has already been uploaded');
} else {
// throw a 500
throw new InternalServerException();
}
}
}
如果由于某种原因必须在此处注入@Res
,则不能使用FilesInterceptor
。然后,您必须自己配置multer
中间件。
您可以创建自定义装饰器来访问userId
:
import { createParamDecorator } from '@nestjs/common';
export const UserId = createParamDecorator((data, req) => {
if (!req.body || !req.body.user_id) {
throw new BadRequestException('No user id given.')
}
return req.body.user_id;
});
,然后在您的控制器方法中使用它,如下所示:
@Post('uploads/avatar')
async uploadFile(@UserId() userId, @UploadedFile() avatar) {