Nestjs 上传文件

Docs: https://docs.nestjs.com/techniques/file-upload

上传单文件

import { FileInterceptor } from '@nestjs/platform-express';

  @Post('upload')
@UseInterceptors(FileInterceptor('file')) // file对应HTML表单的name属性
UploadedFile(@UploadedFile() file, @Body() body){
l(body.name)
const writeImage = createWriteStream(join(__dirname, '..', 'upload', `${file.originalname}`))
writeImage.write(file.buffer)
}

Nestjs  上传文件


上传文件数组

  @Post('upload')
@UseInterceptors(FilesInterceptor('files'))
UploadedFile(@UploadedFiles() files, @Body() body) {
if (!body.name || files.length === 0) {
throw new HttpException('请求参数错误.', HttpStatus.FORBIDDEN)
}
for (const file of files) {
const writeImage = createWriteStream(join(__dirname, '..', 'upload', `${body.name}-${Date.now()}-${file.originalname}`))
writeImage.write(file.buffer)
}
}

Nestjs  上传文件


上传多个字段的文件

  @Post('upload')
@UseInterceptors(FileFieldsInterceptor([{
name: 'front',
maxCount: 1
},
{
name: 'back',
maxCount: 1
},
]))
UploadedFile(@UploadedFiles() files, @Body() body) {
if (!body.name || _.isEmpty(files)) {
throw new HttpException('请求参数错误.', HttpStatus.FORBIDDEN)
} _.each(files, (v: any[], k: string) => {
for (const file of v) {
const writeImage = createWriteStream(join(__dirname, '..', 'upload', `${body.name}-${k}-${Date.now()}-${file.originalname}`))
writeImage.write(file.buffer)
}
})
}

Nestjs  上传文件

上一篇:用javascript编写猜拳游戏(函数)


下一篇:遍历json的方式