美文网首页
NestJS上传文件

NestJS上传文件

作者: Poppy11 | 来源:发表于2021-07-03 17:34 被阅读0次

    这里有一个坑,postman中接收的文件名如果是中文,就会乱码。我去取这个文件流的name,存储到指定位置,则会报错。

    controller层

    import { Body, Controller, Post, UploadedFile, UploadedFiles, UseInterceptors } from '@nestjs/common';
    import { FileFieldsInterceptor, FileInterceptor } from '@nestjs/platform-express';
    import { FileService } from './file.service';
    
    @Controller('file')
    export class FileController {
      constructor(private readonly fileService : FileService){}
      @Post('upload')
      @UseInterceptors(FileFieldsInterceptor([
        { name: 'file', maxCount: 1 },
        { name: 'name', maxCount: 1 },
    ]))
      uploadFile(@UploadedFiles() files,@Body() body) {
        return this.fileService.upload(files,body)
      }
    }
    

    service层

    import { Injectable } from '@nestjs/common';
    import { createWriteStream } from 'fs';
    import { join } from 'path';
    
    @Injectable()
    export class FileService {
      async upload(file,body){
        const fileNmae = body.name
        const fileBuffer = file.file[0]?.buffer
        const fileUrl = "E:/New folder/mobile-exam/backend/public/" + fileNmae
        const writeImage = createWriteStream(join(__dirname, '../../../public', `${fileNmae}`))
        writeImage.write(fileBuffer)
        return fileUrl
      } 
    }
         
    

    相关文章

      网友评论

          本文标题:NestJS上传文件

          本文链接:https://www.haomeiwen.com/subject/ujfpultx.html