使用NestJS和Multer实现动态路径文件上传的请求体获取问题
问题分析与解决方案
问题原因
你在拦截器中提前获取req.body时为空,是因为Multer在解析multipart/form-data请求前,请求体并未被解析。只有当Multer完成文件解析后,req.body才会包含FormData中传递的非文件参数。
此外,你的代码中存在一个拼写错误:file.originalName应为file.originalname(小写n),Multer返回的字段名是驼峰小写格式。
修正后的代码实现
@Injectable() export class CustomFilesInterceptor implements NestInterceptor { constructor(private readonly service: Service) {} async intercept(context: ExecutionContext, next: CallHandler) { const fileIntConst = fileInterceptor('upfile', { storage: multer.diskStorage({ // 使用箭头函数保留类上下文,可直接访问this.service destination: async (req, file, cb) => { // 此时req.body已被Multer解析,包含FormData的非文件参数 const dynamicPath = await this.service.getPath(req.body); cb(null, dynamicPath); }, filename: (req, file, cb) => { cb(null, `${file.originalname}`); }, }), }); const fileInt = new fileIntConst(); return fileInt.intercept(context, next); } }
关键调整说明
- 移除提前获取
req.body的逻辑:将依赖请求体参数的路径生成逻辑移到Multer的destination回调中,此时Multer已完成请求解析,req.body能正确获取FormData中的参数。 - 使用箭头函数绑定上下文:
destination回调用箭头函数编写,确保能访问拦截器类中注入的service实例。 - 修正字段拼写错误:将
originalName改为originalname,匹配Multer返回的文件元数据字段。
内容的提问来源于stack exchange,提问作者sumeet chandel
相关产品推荐
相关产品推荐

