我正在尝试使用内置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);
}
}
在嵌套中,你应该总是避免注入@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) {