org.springframework.web.multipart.MultipartException: 无法解析多部分 servlet 请求...流意外结束

org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request...Stream ended unexpectedly

情况:

正在从 Node.js(通过节点核心 HTTPS 模块)向 spring-boot Java API 提交多部分表单请求。 API 需要两个 form-data 元素:

"route"
"files"

完全错误: Exception processed - Main Exception: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: Stream ended unexpectedly

请求HEADERS:

{"Accept":"*/*",
  "cache-control":"no-cache",
  "Content-Type":"multipart/form-data; boundary=2baac014-7974-49dd-ae87-7ce56c36c9e7",
  "Content-Length":7621}

FORM-DATA 正在写入(全部写入二进制):

Content-Type: multipart/form-data; boundary=2baac014-7974-49dd-ae87-7ce56c36c9e7

--2baac014-7974-49dd-ae87-7ce56c36c9e7

Content-Disposition:form-data; name="route"

...our route object

--2baac014-7974-49dd-ae87-7ce56c36c9e7
Content-Disposition:form-data; name="files"; filename="somefile.xlsx"
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

...excel file contents

--2baac014-7974-49dd-ae87-7ce56c36c9e7--

节点代码:

let mdtHttpMultipart = (options, data = reqParam('data'), cb) => {
  const boundaryUuid = getUuid()
    , baseHeaders = {
        'Accept': '*/*',
        'cache-control': 'no-cache'
      }
    , composedHeaders = Object.assign({}, baseHeaders, options.headers)
    ;

  options.path = checkPath(options.path);

  let composedOptions = Object.assign({}, {
    'host': getEdiHost(),
    'path': buildPathFromObject(options.path, options.urlParams),
    'method': options.method || 'GET',
    'headers': composedHeaders,
    'rejectUnauthorized': false
  });


  composedOptions.headers['Content-Type'] = `multipart/form-data; boundary=${boundaryUuid}`;

  let multipartChunks = [];
  let dumbTotal = 0;

  let writePart = (_, encType = 'binary', skip = false) => {
    if (!_) { return; }

    let buf = Buffer.from(_, encType);
    if (!skip) {dumbTotal += Buffer.byteLength(buf, encType);}
    multipartChunks.push(buf);
  };

  writePart(`Content-Type: multipart/form-data; boundary=${boundaryUuid}\r\n\r\n`, 'binary', true)
  writePart(`--${boundaryUuid}\r\n`)
  writePart(`Content-Disposition:form-data; name="route"\r\n`)
  writePart(JSON.stringify(data[0]) + '\r\n')
  writePart(`--${boundaryUuid}\r\n`)
  writePart(`Content-Disposition:form-data; name="files"; filename="${data[1].name}"\r\n`)
  writePart(`Content-Type:${data[1].contentType}\r\n`)
  writePart(data[1].contents + '\r\n')
  writePart(`\r\n--${boundaryUuid}--\r\n`);

  let multipartBuffer = Buffer.concat(multipartChunks);

  composedOptions.headers['Content-Length'] = dumbTotal;
  let request = https.request(composedOptions);

  // on nextTick write multipart to request
  process.nextTick(() => {
    request.write(multipartBuffer, 'binary');
    request.end();
  });

  // handle response
  request.on('response', (httpRequestResponse) => {
    let chunks = []
      , errObject = handleHttpStatusCodes(httpRequestResponse);
    ;

    if (errObject !== null) {
      return cb(errObject, null);
    }

    httpRequestResponse.on('data', (chunk) => { chunks.push(chunk); });
    httpRequestResponse.on('end', () => {
      let responseString = Buffer.concat(chunks).toString()
        ;

      return cb(null, JSON.parse(responseString));
    });

  });

  request.on('error', (err) => cb(err));
};

根据规范,我们看不出有任何理由抛出 500。对这里的格式进行了大量修改,但我们还没有得到正确的结果。

旁注:它适用于我们使用 POSTMAN,只是无法使用我们自己的应用程序服务器(我们实际构建 excel 文件的地方)。

即使只是尝试的想法,我们也将不胜感激。

是不是你没有在任何地方打电话给request.end()

发送带有正文的请求的(非常通用的)形式是 https.request(opts).end(body)

此外,您可以在每次发送数据时调用 request.write(buf) 而不是累积到一个巨大的缓冲区中(并且您不需要在 nextTick 上执行此操作)(编辑:正如 OP 在评论中指出的那样,这将阻止设置 Content-Length,所以也许保持原样)

试试这个:

let mdtHttpMultipart = (options, data = reqParam('data'), cb) => {
  const boundaryUuid = getUuid()
    , baseHeaders = {
        'Accept': '*/*',
        'cache-control': 'no-cache'
      }
    , composedHeaders = Object.assign({}, baseHeaders, options.headers)
    ;

  let file = data[1]
  let xlsx = file.contents

  options.path = checkPath(options.path);

  let composedOptions = Object.assign({}, {
    'host': getEdiHost(),
    'path': buildPathFromObject(options.path, options.urlParams),
    'method': options.method || 'GET',
    'headers': composedHeaders,
    'rejectUnauthorized': false
  });

  let header = Buffer.from(`--${boundaryUuid}
    Content-Disposition: form-data; name="route"

    ${JSON.stringify(data[0])})
    --${boundaryUuid}
    Content-Disposition: form-data; name="files"; filename="${file.name}"
    Content-Type: ${file.contentType}

  `.replace(/\r?\n */gm, '\r\n'))
  let footer = Buffer.from(`\r\n--${boundaryUuid}--`)
  let length = header.length + xlsx.length + footer.length
  let body = Buffer.concat([header, xlsx, footer], length)

  composedOptions.headers['Content-Length'] = length;
  composedOptions.headers['Content-Type'] = `multipart/form-data; boundary=${boundaryUuid}`;

  let request = https.request(composedOptions);

  // handle response
  request.on('response', (httpRequestResponse) => {
    let chunks = []
      , errObject = handleHttpStatusCodes(httpRequestResponse);
    ;

    if (errObject !== null) {
      return cb(errObject, null);
    }

    httpRequestResponse.on('data', (chunk) => { chunks.push(chunk); });
    httpRequestResponse.on('end', () => {
      let responseString = Buffer.concat(chunks).toString()
        ;

      return cb(null, JSON.parse(responseString));
    });

  });

  request.on('error', (err) => cb(err));

  // write multipart to request
  request.end(body);
};