NestJS上传文件

2021-07-03  本文已影响0人  Poppy11

这里有一个坑,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
  } 
}
     
上一篇下一篇

猜你喜欢

热点阅读