如何在 axios post 请求中同时发送文本和二进制数据?

How to send both text and binary data in axios post request?

我需要找到一个通过单个 axios POST 请求发送的解决方案:

  1. json结构
  2. 二进制文件(excel 文件)

我怎样才能做到这一点?

  let files = event.target.files;
  const fileReader = new FileReader();
  fileReader.readAsText(files[0], null);
  fileReader.onload = () => {
    this.fileContent = fileReader.result;

  let binaryDataForObject = this.fileContent;

  let referenceDataStructure = {
    textData: textDataForObject,
    binaryData: binaryDataForObject,
    referenceDataFileExtension: this.referenceDataFileExtension,
    userProvidedDataTypes: this.columnTypes
  };
  }

  this.axios
    .post(
      "http://url,
      referenceDataStructure
  )

这在技术上可行,但在 java 方面我无法弄清楚如何解码二进制数据(编码为字符串)以便将其视为 excel 文件。

提前感谢您的任何有意义的回复。 鲁博斯.

  1. 通过简单的 POST 请求,您最多只能发送 1mb 的二进制数据
  2. 要在一个请求中发送二进制和文本,您应该使用 FormData

查看 了解信息

更新 14.12

我在最近的项目中是如何做到这一点的是使用 FormData

所以首先你需要将文件作为 blob:

const fileReader = new FileReader()
// Here we will get the file as binary data
fileReader.onload = () => {
  const MB = 1000000;
  const Blob = new Blob([fileReader.result], {
                   // This will set the mimetype of the file
                   type: fileInputRef.current.files[0].type
                 });
  const BlobName = fileInputRef.current.files[0].name;
  if (Blob.size > MB) return new Error('File size is to big');

  // Initializing form data and passing the file as a param
  const formData = new FormData();
  // file - field name, this will help you to read file on backend
  // Blob - main data to send
  // BlobName - name of the file, default it will be name of your input
  formData.append('file', Blob, BlobName);

  // Append json data
  formData.apped('some-key', someValue)

  // then just send it as a body with post request
  fetch('/api/submit-some-form-with-file', {
    method: 'POST',
    body: formData
  })
  // Handle the rest
  .then()
}

fileReader.readAsArrayBuffer(fileInputRef.current.files[0])

您可以将此示例包装在 react 中的 handle submit 函数中,并喜欢或按原样使用它