如何格式化formData对象的结构以匹配后端期望的内容?

时间:2019-03-30 03:41:06

标签: ruby-on-rails react-native multipartform-data expo react-native-image-picker

我正在使用formData张贴通过ImagePicker上传的图像。我正在像这样发送参数:

  let formData = new FormData();

  formData.append('image', { uri: localUri, name: filename, type });
  formData.append('description', 'this is the decription');

  return await fetch('https://prana-app.herokuapp.com/v1/visions/', {
    method: 'POST',
    body: formData,
    header: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-User-Email': this.state.email,
      'X-User-Token': this.state.accessToken
    },
  });
  };

这似乎不起作用,因为我得到了一个非常通用的NoMethodError (undefined method build'for nil:NilClass):`错误。

假设image参数是图像,而description参数是字符串,我如何以正确的方式发布参数?

谢谢

1 个答案:

答案 0 :(得分:0)

使用Formdata时,Content-Type必须不同。

example.js:

fileSend = () => {
    const apiUrl = "http://00.000.00.000:0000/upload";
    const uri = this.state.image;
    const stringdata = {
      username: this.state.name,
      introduce: this.state.introducetext,
      addresstext: this.state.addresstext
    };
    const uriParts = uri.split(".");
    const fileType = uriParts[uriParts.length - 1];
    const formData = new FormData();

    formData.append("userfile", {
      uri,
      name: `photo.${fileType}`,
      type: `image/${fileType}`
    });
    for (var k in stringdata) {
      formData.append(k, stringdata[k]);
    }

    const options = {
      method: "POST",
      body: formData,

      headers: {
        Accept: "application/json",
        "Content-Type": "multipart/form-data"
      }
    };

    return fetch(apiUrl, options)

如上面的示例所示,如果Stringdata不是一个,Content-Type应该写multipart/form-data并将其传递给For ... in