Type of object received during file upload using @UploadFile

In the REST API below, what is the type of file object that is received.

@Post('/:folderId/documents/:fileName')
@UseInterceptors(FileInterceptor('file'))
@ApiConsumes('multipart/form-data')
@ApiImplicitParam({ name: 'folderId', description: ' Folder Id' })
@ApiImplicitParam({ name: 'fileName', description: ' File Name' })
@ApiImplicitFile({ name: 'file', required: true, description: 'PDF File' })
async uploadFile(@UploadedFile() file, @Param() folderId, @Param() fileName) {
/**
 * I need to know the type of file object (first argument) of uploadFile
 */
    this.folderService.uploadFile(file, folderId, fileName);
}

I need to write a file received in the request to disk. How to do that?

Answers:

Answer

You can save the file by specifying a destination path in the MulterOptions:

// files will be saved in the /uploads folder
@UseInterceptors(FileInterceptor('file', {dest: 'uploads'}))

If you want more control over how your file is saved, you can create a multer diskStorage configuration object instead:

import { diskStorage } from 'multer';

export const myStorage = diskStorage({
  // Specify where to save the file
  destination: (req, file, cb) => {
    cb(null, 'uploads');
  },
  // Specify the file name
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  },
});

And then pass it to the storage property in your controller.

@UseInterceptors(FileInterceptor('file', {storage: myStorage}))

For more configuration options, see the multer docs.

Answer

You can import the type from the package. '@types/multer' and then qualify the file as:

        @UploadedFile() file: Express.Multer.File,

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/multer/index.d.ts#L103

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.