Reputation: 292
I try to make a simple file upload REST interface using NEST.JS and MULTER -- but its not working. I am able to POST a binary file debug.log to the URL, and I see the "Hello undefined" message, but the uploaded file neither is created at the given folder uploads nor it is rejected because the extension is not correct - according to the file filter. However, no exception or error is shown.
Why is multer not working? Why is the @Uploadedfile() file shown as undefined?
Thanks
import { Controller, Post, Request, UseInterceptors, FileInterceptor, UploadedFile, HttpCode, HttpException, HttpStatus } from '@nestjs/common';
import { diskStorage, File } from 'multer';
const path = require('path');
const myStorage = diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads/');
},
limits: { fileSize: 1000000 },
fileFilter: function (req, file, cb) {
const extension = path.extname(file.originalname).toLowerCase()
const mimetyp = file.mimetype
if (extension !== '.jpg' || mimetyp !== 'image/jpg') {
cb(new HttpException('Only images are allowed', HttpStatus.NOT_ACCEPTABLE));
}
cb(null, true);
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '.jpg');
}
});
@Controller('documents')
export class DocumentsController {
@Post()
@HttpCode(HttpStatus.OK)
@UseInterceptors(FileInterceptor('file', { storage: myStorage }))
public async addDocument(@UploadedFile() file): Promise<any> {
console.log("Hello " + file);
}
}
Upvotes: 6
Views: 8071
Reputation: 597
if your issue was that it console.log shows "undefined" , use swagger instead of postman, i had the same issue
Upvotes: 0
Reputation: 627
I know it's a late reply for the person who asked this question, but the answer is for the people who will face it in the future.
First, check the nestjs documentation
If MulterModule
registered in the *.module.ts
file it creates the upload directory outside of the src
folder. which is a good practice.
MulterModule.register({
dest: './upload',
});
If there is a need to change the destination directory use destination: String|callback
from DiskStorageOptions
or dest:string
from FileInterceptor
. For upload path use like src/../upload
to keep the folder outside the src
directory.
Other problems from the above code mentioned in the question:
reason console.log("Hello " + file);
here file is Object
and trying concatenate with String
.
change it to console.log("Hello ", file);
the extension is not correct, no exception or error is shown
fileFilter: function (req, file, cb) {
const extension = path.extname(file.originalname).toLowerCase()
const mimetyp = file.mimetype
if (extension !== '.jpg' || mimetyp !== 'image/jpg') {
cb(new HttpException('Only images are allowed', HttpStatus.NOT_ACCEPTABLE));
}
cb(null, true);
}
Here need to add a return
.
Upvotes: 2