nestjs - 使用 nestjs 和 multer 上传文件

标签 nestjs

由于 nestjs 是一个 express 应用程序,因此可以使用任何库来处理使用 nest 的上传,并且由于它提供了中间件,因此也可以使用 multer。我的问题是:使用 nestjs 处理文件上传的最佳方法是什么?

最佳答案

正如@Kamyl 在问题 https://github.com/nestjs/nest/issues/262 上所告知的那样, 自 v4.6.0可以使用通用文件拦截器使用multer将文件上传到nestjs。

import { ... , UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common'

... 

@UseInterceptors(FileInterceptor('file'))
async upload( @UploadedFile() file) {
  console.log(file)
}

这样变量file会有 buffer
使用 Multer 选项

还需要字段名称作为第一个参数,然后是一个带有 Multer 选项的数组
import { ... , UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common'
import { diskStorage } from 'multer'
import { extname } from 'path'

...

@UseInterceptors(FileInterceptor('file', {
  storage: diskStorage({
    destination: './uploads'
    , filename: (req, file, cb) => {
      // Generating a 32 random chars long string
      const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
      //Calling the callback passing the random name generated with the original extension name
      cb(null, `${randomName}${extname(file.originalname)}`)
    }
  })
}))
async upload( @UploadedFile() file) {
  console.log(file)
}

这样变量file会有 filename , destinationpath .
destination来自 diskStorage 的参数也可以是一个函数,参数和期望回调与filename相同.通过传递 diskStorage文件将自动保存到指定文件名的目的地。

也可以使用 @UploadedFiles 处理多个文件和 FilesInterceptor (复数)

关于nestjs - 使用 nestjs 和 multer 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49096068/

相关文章:

javascript - NestJS - JWTModule 上下文依赖

node.js - 带有 NestJS 的 Facebook Passport

javascript - NestJs SSL : error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

node.js - 带有自定义 "company_id" header 的 GET 请求在本地有效,但 header 不存在于 GCP App Engine 中

nestjs - NestJs+TypeOrm中如何调用存储过程(后端)

node.js - 使用 GraphQL NestJS 上传

node.js - mongodb不显示嵌入对象_id

typescript - 如何使用类验证器验证嵌套 js 中的 uuid 数组?

azure - Nestjs - 实现 Azure-Ad Passport 身份验证

node.js - MongoDB、Mongoose 和 Apollo GraphQL 在文档中定义 _id 类型