如何ajax POST json 数据和文件?

How to ajax POST json data along with files?

我目前正在更改 React 项目中的表单,以允许随表单一起上传文件。目前 ajax post 看起来像下面这样:

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

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

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

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

我也在使用 rails 后端,如果我可以做些什么来让事情变得更容易的话。

我通过创建一个方法将 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);
  }
}