nestjs功能:⬆️ 文件上传

3,327 阅读1分钟

依赖: multer 支持传输数据: multipart/form-data

如何使用

  1. Post 方法
  2. UseInterceptors 使用拦截器
  3. FileInterceptor(fieldName, options) 文件拦截器
  4. UploadedFile 上传装饰器
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file) {
  console.log(file);
}

文件数组

文件拦截器 FileInterceptor 需要支持三个参数:

  • fieldName
  • maxCount
  • options

我们看到其实只是文件装饰器装饰器发生了变化:UploadedFiles

@Post('upload')
@UseInterceptors(FileInterceptor('files'))
uploadFile(@UploadedFiles() files) {
  console.log(files);
}

多文件

FileFieldsInterceptor 文件拦截器接收一个数组作为参数,数组保存了对上传数据的描述。描述的字段:

  • name
  • maxCount
@Post('upload')
@UseInterceptors(FileFieldsInterceptor([
  { name: 'avatar', maxCount: 1 },
  { name: 'background', maxCount: 1 },
]))
uploadFile(@UploadedFiles() files) {
  console.log(files);
}

文件数组上传的时候,也是拦截器装饰器发生了变化, 使用了 FileFieldsInterceptor 文件字段装饰器。

任何文件

使用任何文件拦截装饰器 AnyFilesInterceptor, 拦截器部分发生了改变

multer 的默认选项配置

使用模块的 MulterModule.register 方法,在 express 中的 multer 的 options:

  • dest 文件存储位置
  • fileFilter 过滤文件类型
  • limits 限制文件数量
  • preservePath 使用全路径

异步配置

前面我们配置 multerModule 的时候 options 是 register 同步配置,我们也可以使用 registerAsync 进行异步配置。

异步配置使用工厂函数: useFactory 来配置 options。 当然我们也能使用 import 来支持模块。使用 inject 来注入服务。

小结

  1. 上传使用了 express 平台的 multer 包处理文件上传,其次 只能处理表单数据 multipart/form-data 的表单能力。
  2. 上传有不同的任务:
    • 普通文件上传拦截器和文件装饰器 FileInterceptor/UploadedFile
    • 多文件上传拦截器和文件装饰器 FilesInterceptor/ UploadedFiles
    • 数组文件拦截器和文件装饰器 FileFieldsInterceptor/UploadedFiles
  3. 配置 multer
  4. 异步配置 multer