【问题标题】:Multipart: Boundary not found - upload file (using multer)多部分:未找到边界 - 上传文件(使用 multer)
【发布时间】:2021-08-22 12:07:36
【问题描述】:

我正在使用 multer 上传文件,它似乎在 api 端工作,但这是前端的问题:

fetch(`${path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    body: file,
  }).then((response) => {
    return response.status;
  });

如果我添加“multipart/form-data”,则会出现错误:“Multipart: Boundary not found”

否则,控制器中的“文件”未定义

这里是控制器:

@ApiConsumes('multipart/form-data')
  @ApiFile('file')
  @UseInterceptors(
    FileInterceptor('file', multerOptions([MimeExtEnum.XLS, MimeExtEnum.XLSX])),
  )
  @Post('/uploadFile')
  public async uploadFile(
    @UploadedFile() file,
  ): Promise<any> {
      console.log("file", file); //here the file is undefined
  }

【问题讨论】:

    标签: reactjs file-upload multipartform-data multer


    【解决方案1】:

    当您在前端发送带有 fetch 的表单时,不要自己设置 Content-Type 标头。如果这样做,它将没有表单边界,并且 multipart/form-data 请求将在后端被错误地解析。

    您可以省略标题,因为浏览器会为您设置它,其中包括一个唯一的边界。

    • 您的标题:Content-Type=multipart/form-data;
    • 浏览器标题:Content-Type=multipart/form-data; boundary=------WebKitFormBoundaryg7okV37G7Gfll2hf--

    其次,要发送文件,您需要先使用FormData API 构造一个表单,将文件附加到其中,然后将表单发送到后端。

    它的外观如下:

    // Construct a form and append the file to it
    const form = new FormData();
    form.append('file', file);
    
    // Send multipart/form-data request with fetch
    // Note: don't set `Content-Type` header manually, the browser does this for you
    fetch(`${path}`, {
      method: 'POST',
      body: form,
    }).then((response) => {
      return response.status;
    });
    

    【讨论】:

      猜你喜欢
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 2020-10-18
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      相关资源
      最近更新 更多