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

  • 相关阅读:
    Dijkstra-leetcode 743.网络延迟时间
    BFS-leetcode787 K站中转内最便宜的航班
    图论基础——单源最短路径问题
    DFS leetcode-547 朋友圈
    SpringBoot 使用注解向容器中注册Bean的方法总结
    SpringBoot对SpringMVC的支持
    数据源简介
    Spring MVC简介
    2020-2-10 Python 列表切片陷阱:引用、复制与深复制
    2020-2-2 语法糖
  • 原文地址:https://www.cnblogs.com/ajanuw/p/9575278.html
Copyright © 2011-2022 走看看