使用@UploadFile上传文件时收到的对象类型

时间:2018-12-06 10:14:56

标签: javascript node.js file-upload multer nestjs

在下面的REST API中,接收到的文件对象的类型是什么。

@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);
}

我需要将请求中收到的文件写入磁盘。该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以通过在MulterOptions中指定目标路径来保存文件:

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

如果您想进一步控制文件的保存方式,则可以创建一个multer diskStorage配置对象:

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);
  },
});

然后将其传递到控制器中的storage属性。

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

有关更多配置选项,请参见multer docs

答案 1 :(得分:0)

您可以从包中导入类型。 '@types/multer',然后将文件限定为:

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

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

答案 2 :(得分:0)

试试这个...

@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}`);
    }

查看更多信息 - https://www.techiediaries.com/nestjs-upload-serve-static-file/