NestJS+React项目上传PDF时出现filename未定义错误
NestJS + React项目PDF上传报错排查:Cannot read properties of undefined (reading 'filename')
问题描述
- 开发基于NestJS和React的项目时,添加PDF文档触发错误:
Cannot read properties of undefined (reading 'filename') - 后端通过Postman以Form Data形式测试上传功能正常,但前端调用时返回500内部服务器错误:
xhr.js:247 POST http://localhost:3000/candidates 500 (Internal Server Error)
相关代码
multer.config.ts
import { diskStorage } from 'multer'; import * as path from 'path'; // add this line to import the path module export const multerConfig = { dest: './uploads', storage: diskStorage({ destination: './uploads', filename: (req, file, cb) => { const filename = `${Date.now()}_${file.originalname}`; cb(null, filename); }, }), fileFilter: (req, file, cb) => { const filetypes = /pdf/; const mimetype = filetypes.test(file.mimetype); const extname = filetypes.test(path.extname(file.originalname).toLowerCase()); if (mimetype && extname) { return cb(null, true); } cb(new Error('Only PDF files are allowed')); }, };
服务层方法
async create(createCandidats: CreateCandidats, user: User): Promise<Candidate> { const { email, username, documents } = createCandidats; const candidate = new Candidate(); candidate.email = email; candidate.documents = documents; candidate.username = username; candidate.user = user; return await this.candidateRepository.save(candidate); }
控制器代码
@Post() @Roles(Role.Admin) @UseGuards(AuthGuard()) @UseInterceptors(FileInterceptor('document')) async create( @UploadedFile() document: Express.Multer.File, @Body() createCandidats: CreateCandidats, @GetUser() user: User ): Promise<Candidate> { console.log("check the documents in express multer",document) console.log('1===>',createCandidats) const documentName = document.filename; console.log('2===>',document.filename) createCandidats.documents = documentName; return await this.candidateService.create(createCandidats, user); }
问题排查与解决方案
核心原因
Postman测试正常但前端报错,本质是前端请求的Form Data文件字段名与后端接收的不匹配,或前端未正确以Form Data格式发送文件。后端控制器通过FileInterceptor('document')指定接收名为document的文件字段,若前端传参的key不是document,document变量会变为undefined,进而触发读取filename的报错。
具体修复步骤
- 统一前后端Form Data字段名
确保前端构造Form Data时,文件对应的key为document,示例React代码:const formData = new FormData(); formData.append('document', file); // 此处key必须与后端的'document'一致 formData.append('email', 'xxx@example.com'); formData.append('username', 'xxx'); // 发送请求时需指定Content-Type为multipart/form-data axios.post('/candidates', formData, { headers: { 'Content-Type': 'multipart/form-data' } }); - 后端增加参数校验
在控制器中先判断文件是否存在,避免崩溃:async create( @UploadedFile() document: Express.Multer.File, @Body() createCandidats: CreateCandidats, @GetUser() user: User ): Promise<Candidate> { if (!document) { throw new BadRequestException('请上传PDF文件'); } const documentName = document.filename; createCandidats.documents = documentName; return await this.candidateService.create(createCandidats, user); } - 确认Multer配置全局注册
确保在NestJS对应模块中正确注册Multer配置,示例AppModule代码:import { Module } from '@nestjs/common'; import { MulterModule } from '@nestjs/platform-express'; import { multerConfig } from './multer.config'; @Module({ imports: [MulterModule.register(multerConfig)], // 其他模块配置 }) export class AppModule {}
内容的提问来源于stack exchange,提问作者Yassine jdidi
相关产品推荐
相关产品推荐

