在Nest.js中,当我想发送一个带有表单数据的请求时,该表单数据可能包含也可能不包含文件附件,那么我就无法在同一个请求中同时获得主体请求和文件,也无法验证主体请求的字段是否有效.

import {
  Body,
  Controller,
  MaxFileSizeValidator,
  ParseFilePipe,
  Post,
  UploadedFile,
  UseInterceptors,
} from "@nestjs/common";
import { JoiValidationPipe } from "../../pipes/validation/joi-validation.pipe";
import { UserValidatorSchema } from "./validator/account-register.validator";
import { CreateUserDto } from "./dtos/account-register.dto";
import { AccountRegisterService } from "./account-register.service";
import { FileInterceptor } from "@nestjs/platform-express";
import { MAX_FILE_SIZE } from "../../constants/multer.constants";

@Controller("user")
export class FormdataWithFileController {
  constructor(private readonly _formdataWithFileService: formdataWithFileService) {}

  @Post("formdataWithFile")
  @UseInterceptors(FileInterceptor("file"))
  private async Signup(
    @UploadedFile(
      new ParseFilePipe({
        validators: [
          new MaxFileSizeValidator({ maxSize: MAX_FILE_SIZE })
        ],
      })
    )
    file,
  ) {
    return await this._formdataWithFileService.execute(file);
  }
}

推荐答案

fileIsRequired: false放入@UploadedFile()管道中,以使文件成为可选的.

@Body(new JoiValidationPipe<CreateUserDto>(UserValidatorSchema)) : body CreateUserDto)名装饰师将进行车身验证.

import {
  Body,
  Controller,
  MaxFileSizeValidator,
  ParseFilePipe,
  Post,
  UploadedFile,
  UseInterceptors,
} from "@nestjs/common";
import { JoiValidationPipe } from "../../pipes/validation/joi-validation.pipe";
import { UserValidatorSchema } from "./validator/account-register.validator";
import { CreateUserDto } from "./dtos/account-register.dto";
import { AccountRegisterService } from "./account-register.service";
import { FileInterceptor } from "@nestjs/platform-express";
import { MAX_FILE_SIZE } from "../../constants/multer.constants";

@Controller("user")
export class FormdataWithFileController {
  //
  constructor(private _formdataWithFileService: FormdataWithFileService) {}

  @Post("formdataWithFile")
  @UseInterceptors(FileInterceptor("file"))
  private async Signup(
    @UploadedFile(
      new ParseFilePipe({
        validators: [
          new MaxFileSizeValidator({ maxSize: MAX_FILE_SIZE }),
          // new FileTypeValidator({ fileType: "image/jpeg" }),
        ],
        fileIsRequired: false,
      })
    )
    file,
    @Body(new JoiValidationPipe<CreateUserDto>(UserValidatorSchema)) body: CreateUserDto
  ) {
    // acccess file & body data
    const fileWithBody = {
      body,
      file
    };
    return await this._formdataWithFileService.execute(fileWithBody)
  }
}

Node.js相关问答推荐

查询嵌套数组中的最后一个元素具有特定值的mongoDB集合中的文档

运行JEST测试时找不到模块&q;错误

如何在MEVN堆栈中结合创建和更新表单流程?

在内存中加载安全密钥安全吗?还是每次都从文件中读取?

在对象的嵌套数组中使用$lookup,创建多个记录作为响应,mongodb

谷歌应用程序脚本UrlFetchApp和nodejs-axios返回不同的结果;MyFitnessPal日记

如何在docker容器上正确安装nodejs?

Rest-Api动态图像路径和Express除非

如何修复我的 NodeJS SSE 写入函数以在后续调用中更新 HTML?

node-gyp: "..\src\binding.cc: 没有这样的文件或目录"

为什么我的react 表单不能正常工作?

在数组的另一个对象中获取数组的mongoose 对象

AWS EC2 npm install 突然很慢

fs.writefile 选项参数的可能值,尤其是只读文件的整数

node.js 是否支持yields ?

npm publish 导致'错误:EPERM:不允许操作,取消链接...',errno -4048

Node.js -Firebase 服务帐户私钥不会解析

Bootstrap 中的 Grunt 依赖冲突

npm install - javascript堆内存不足

CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权