【问题标题】:How to send both text and binary data in axios post request?如何在 axios 发布请求中同时发送文本和二进制数据?
【发布时间】:2022-01-15 04:01:21
【问题描述】:

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

提前感谢您提供任何有意义的回复。 卢布斯。

【问题讨论】:

    标签: javascript java post axios


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

    查看this answer 了解信息

    更新 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 和 like 中的句柄提交函数中,或按原样使用它

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • 谢谢!这对我找到解决问题的方法有很大帮助。
    猜你喜欢
    • 2021-08-28
    • 2020-05-12
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2019-03-04
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多