I have a rather weird issue with Nestjs in combination with Multer and the Nestjs builtin file interceptor. Locally, when I run the API, it seems to be working perfectly, but as soon as I push it to the server, the API gets stuck before executing the actual controller logic and times out after that. I tested if the file was saved correctly and this seemed to be working as well. We also have another route where this works as expected with the same setup and even the same destination folder. So now my question is what could cause this behavior in Nest?
The service runs in a Docker container, the only difference is that I test it locally on my Macbook and the server runs Debian12, however i don’t think that this is related, execpt for file and folder permissions perhaps?
@Post('analyze')
@UseInterceptors(FileInterceptor('file', {
storage: diskStorage({
destination: '/app/uploads/documents', // Make sure this directory exists
filename: (req, file, callback) => {
const name = file.originalname.split('.')[0].replace(/ /g, "");
const fileExtName = 'png';
const randomName = Array(32)
.fill(null)
.map(() => Math.round(Math.random() * 16).toString(16))
.join('');
callback(null, `${name}-${randomName}.${fileExtName}`);
},
}),
fileFilter: (req, file, cb) => {
if (file.mimetype.startsWith('image/png')) {
console.log('File is png: ', file);
cb(null, true);
} else {
cb(null, false);
console.log('File is not png: ', file);
}
}
})
)
async uploadDocument(@AuthenticatedUser() user: any, @UploadedFile(new ParseFilePipeBuilder()
.addFileTypeValidator({
fileType: 'image/png',
})
.build({
fileIsRequired: false,
}),) file: Express.Multer.File): Promise<string> {
console.log('Uploading file: ', file);
if (file) {
try{
const doc = await this.documentService.analyze(file, user.email);
return JSON.stringify(doc);
} catch (error) {
throw error;
}
}
else {
throw new HttpException('Only png images are accepted!', 400);
}
}
I already tried deleting the folder before starting the API service, so that the folder is created initially inside the Docker container, instead of on the host. The controller then works at the beginning and then for some reason stops executing again after some time.
I am not entirely sure if it is related to the host filesystem or rather Nest itself or neither.
5av3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.