Hey everyone, I'm currently working on a project using nestjs and reactjs. I encountered an error when trying to add a document that reads: "Cannot read properties of undefined (reading 'filename') in multer.config.ts"
import { diskStorage } from 'multer';
import * as path from 'path'; // Make sure to 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'));
},
};
Here is the service method:
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);
}
And this is the controller section:
@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);
I have a POST method set up to upload a pdf document in the backend, which works fine with Postman's form data test. However, I encounter the error "Cannot read properties of undefined (reading 'filename')" when testing it on the frontend xhr.js:247 POST http://localhost:3000/candidates 500 (Internal Server Error)