Amit Dube
Amit Dube

Reputation: 1027

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?

Upvotes: 9

Views: 6284

Answers (3)

Syam
Syam

Reputation: 21

try this...

@Post(':userid/avatar')
    @UseInterceptors(FileInterceptor('file',
      {
        storage: diskStorage({
          destination: './avatars', 
          filename: (req, file, cb) => {
          const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
          return cb(null, `${randomName}${extname(file.originalname)}`)
        }
        })
      }
    )
    )
    uploadAvatar(@Param('userid') userId, @UploadedFile() file) {
      this.userService.setAvatar(Number(userId), `${this.SERVER_URL}${file.path}`);
    }

check this out for more info - https://www.techiediaries.com/nestjs-upload-serve-static-file/

Upvotes: 2

christophercotton
christophercotton

Reputation: 5859

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

Upvotes: 20

Kim Kern
Kim Kern

Reputation: 60357

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.

Upvotes: 5

Related Questions