nestjs上传文件

官方文档

目标

前端调用接口上传文件,将文件存储到服务端 /public/upload/ 目录中,接口返回文件路径

注意:示例代码都使用app模块为例,实际可放到任意模块

上传文件

app.controller.ts 新增接口声明

import { Controller, Get, Post, UploadedFile, UploadedFiles, UseInterceptors } from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  // 单个上传文件
  @Post('uploadFile')
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(@UploadedFile() file): any {
    return this.appService.uploadFile(file);
  }

  // 批量上传文件
  @Post('uploadFileBatch')
  @UseInterceptors(FilesInterceptor('files'))
  uploadFileBatch(@UploadedFiles() files): any {
    return this.appService.uploadFileBatch(files);
  }
}

app.service.ts 新增单个文件上传和批量上传的方法

import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import { join } from 'path';

@Injectable()
export class AppService {

  // 单个文件上传
  async uploadFile(file) {
    if (file) {
      const allowedMimeTypes = ['image/jpeg', 'image/png']; // 设置允许上传的文件类型   
      if (!allowedMimeTypes.includes(file.mimetype)) {
        return {
          success: false,
          msg: '文件格式不正确'
        }
      }
      // 注意:使用swagger上传文件,中文会乱码
      const fileName = `${Date.now()}-${file.originalname}`; // 生成文件名(这里使用了当前时间戳)
      const filePath = join(__dirname, '..', 'public/upload/' + fileName); // 构造文件路径
      fs.writeFileSync(filePath, file.buffer); // 写入文件内容
      return {
        success: true,
        data: '/upload/' + fileName
      }
    } else {
      return {
        success: false,
        msg: '请上传文件'
      }
    }
  }

  // 批量上传文件
  async uploadFileBatch(files) {
    if (files) {
      const filesUrlList = []; // 文件路径集合,将上传后的文件路径返回给前端
      for (const item of files) {
        const fileName = `${Date.now()}-${item.originalname}`; // 生成文件名(这里使用了当前时间戳)
        const filePath = join(__dirname, '..', 'public/upload/' + fileName); // 构造文件路径
        fs.writeFileSync(filePath, item.buffer); // 写入文件内容
        filesUrlList.push('/upload/' + fileName);
      }
      return {
        success: true,
        data: filesUrlList
      }
    } else {
      return {
        success: false,
        msg: '请上传文件'
      }
    }
  }
}

暴露静态文件目录

官方文档

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { join } from 'path';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 配置模板引擎,暴露public目录
  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

  await app.listen(3000);
}
bootstrap();

注意

swagger ui 调用上传文件,中文会乱码。原因是swagger ui字符集为ISO-8859-1,无法识别中文。

可以针对该场景转换字符集

decodeURIComponent(escape(file.originalname))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值