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

3

我需要找到一种解决方案,通过单个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文件。

非常感谢您提供有意义的回复。 Lubos.

1个回答

4
  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的handleSubmit函数中,或者像现在一样直接使用它。


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community
谢谢!这帮助我很多,找到了解决我的问题的方法。 - LubosD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接