【问题标题】:How to ajax POST json data along with files?如何将 POST json 数据与文件一起 ajax?
【发布时间】:2019-02-15 20:26:03
【问题描述】:

我目前正在更改 React 项目中的表单,以允许随表单一起上传文件。目前,ajax 帖子如下所示:

return axios.post(url, {
      item: {
        prop: 'test',
        otherProp: 'test2'
        arrayOfObjects: [
          {
            prop: 'test'
          },
          {
            prop: 'test'
          },
        ]
      }
    });

现在的问题是我需要发送多张图片与其他表单数据一起上传。

我所看到的一切都说使用FormData,但问题是我有很多嵌套数组和对象字面量,这使得使用FormData 相当复杂。

我是否可以在不增加复杂性的情况下提交多个文件以及我的 JSON 数据?

如果我可以在这方面做任何事情来让事情变得更容易,我也会使用 rails 后端。

【问题讨论】:

  • FormData 是这样做的方法,也许您需要查看您的数据结构,因为听起来问题确实存在?
  • 我做了一个递归方法将我的 json 对象转换为 FormData 对象,我认为这是我最好的解决方案。我已经更新了我的原始帖子以显示它。

标签: javascript ajax reactjs axios multipartform-data


【解决方案1】:

我通过创建将 json 数据转换为 FormData 对象的方法解决了这个问题。

function convertToFormData(data) {
  var fd = new FormData();
  convertToFormDataRecursive(fd, '', data);
  return fd;
}

function convertToFormDataRecursive(formData, key, data) {
  if (moment.isMoment(data)) {
    convertToFormData(formData, key, data.toString());
  }
  else if (data instanceof File) {
    formData.append(key, data, data.name);
  }
  else if (data instanceof Array) {
    for (let i = 0; i < data.length; i++) {
      convertToFormDataRecursive(formData, key + '[' + i + ']', data[i]);
    }
  }
  else if (data instanceof Object) {
    for (let prop in data ) {
      var newKey = (key != '') ? key + '[' + prop + ']' : prop;
      convertToFormDataRecursive(formData, newKey, data[prop]);
    }
  }
  else {
    formData.append(key, data);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2021-07-29
    • 2017-04-08
    • 2017-03-14
    相关资源
    最近更新 更多