官方文档
目标
前端调用接口上传文件,将文件存储到服务端 /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))