文件上传
About 1 min
详见:文件上传
1. 创建文件上传模块
nest g module upload
nest g controller upload
nest g service upload
2. 安装相关包
要处理文件上传,Nest提供了一个基于multer中间件包的内置模块:
npm install --save multer
为了更好的类型安全性,让我们安装multer的类型定义包:
npm i -D @types/multer
3. 基本使用
要上传单个文件,只需将FileInterceptor()
拦截器绑定到路由处理程序,并使用@UploadedFile()
装饰器从请求中提取file
// upload.controller.ts
import {
Controller,
Post,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
@Controller('upload')
export class UploadController {
@Post()
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file: Express.Multer.File) {
console.log(file);
}
}
4. 文件验证
使用管道Pipe并将其绑定到使用 @UploadedFile()
装饰器注解的参数上,可以验证传入的文件元数据
我们在upload文件夹下创建一个fileSize.pipe.ts
,实现一个基本的文件大小验证器 Pipe:
// fileSize.pipe.ts
import {
PipeTransform,
Injectable,
ArgumentMetadata,
BadRequestException,
} from '@nestjs/common';
@Injectable()
export class FileSizeValidationPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
// "value" is an object containing the file's attributes and metadata
const oneKb = 1000;
if (value.size < oneKb * 100) {
return value;
} else {
throw new BadRequestException('文件大小超过100kb');
}
}
}
绑定管道:
// upload.controller.ts
import {
Controller,
Post,
UploadedFile,
UseInterceptors,
UsePipes,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { FileSizeValidationPipe } from './fileSize.pipe';
@Controller('upload')
export class UploadController {
@Post()
@UseInterceptors(FileInterceptor('file'))
@UsePipes(FileSizeValidationPipe)
uploadFile(@UploadedFile() file: Express.Multer.File) {
return file;
}
}