Why is my Upload-File POST not working using NEST.JS and Multer?
Asked Answered
W

2

6

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);
    }
}
Waggoner answered 17/11, 2019 at 15:33 Comment(3)
I have encountered the same problemHustings
I had the same problem. use UploadedFiles decorator instead (note the final "s").Coreligionist
Did you register/import MulterModule on your respective module where your file uploaded API exists ? It would be like this /* MulterModule.register({ dest: './yourDestFolder', }); */Sheffield
D
2

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:

  • I see the "Hello undefined" message

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.

Dipsomaniac answered 1/5, 2021 at 16:13 Comment(0)
T
0

if your issue was that it console.log shows "undefined" , use swagger instead of postman, i had the same issue

Theressa answered 14/2 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.