zoukankan      html  css  js  c++  java
  • Nestjs 上传文件

    $ npm i -D @types/multer
    

    上传单文件

    import { Post, UseInterceptors, UploadedFile } from '@nestjs/common';
    import { FileInterceptor } from '@nestjs/platform-express';
    
      @Post('upload')
      @UseInterceptors(FileInterceptor('file')) // file对应HTML表单的name属性
      UploadedFile(@UploadedFile() file: Express.Multer.File, @Body() body){
        l(body.name)
        const writeImage = createWriteStream(join(__dirname, '..', 'upload', `${file.originalname}`))
        writeImage.write(file.buffer)
      }
    

    上传文件数组

      @Post('upload')
      @UseInterceptors(FilesInterceptor('files'))
      UploadedFile(@UploadedFiles() files, @Body() body) {
        if (!body.name || files.length === 0) {
          throw new HttpException('请求参数错误.', HttpStatus.FORBIDDEN)
        }
        for (const file of files) {
          const writeImage = createWriteStream(join(__dirname, '..', 'upload', `${body.name}-${Date.now()}-${file.originalname}`))
          writeImage.write(file.buffer)
        }
      }
    


    上传多个字段的文件

      @Post('upload')
      @UseInterceptors(FileFieldsInterceptor([{
          name: 'front',
          maxCount: 1
        },
        {
          name: 'back',
          maxCount: 1
        },
      ]))
      UploadedFile(@UploadedFiles() files, @Body() body) {
        if (!body.name || _.isEmpty(files)) {
          throw new HttpException('请求参数错误.', HttpStatus.FORBIDDEN)
        }
    
        _.each(files, (v: any[], k: string) => {
          for (const file of v) {
            const writeImage = createWriteStream(join(__dirname, '..', 'upload', `${body.name}-${k}-${Date.now()}-${file.originalname}`))
            writeImage.write(file.buffer)
          }
        })
      }
    

  • 相关阅读:
    【解决火车轮播图小圆点跳的问题】传统轮播图-三位法
    jq龙禧轮播图
    QT MSVC环境中添加QWT
    XDMA ip core的使用
    PCIe基础知识与例程分析----PIO_demo
    Day04 (四)_TCP文件传输设计
    Day04 (三)_UDP传输端设计
    Day04 (二)_TCP传输客户器端设计
    Day04 (一)_TCP传输服务器端设计
    Day03 (下)_Qt文件系统
  • 原文地址:https://www.cnblogs.com/ajanuw/p/9575278.html
Copyright © 2011-2022 走看看