0

我正在使用 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的构建' nil:NilClass):` 错误。

image鉴于参数是图像并且description参数是字符串,我如何以正确的方式发布参数?

谢谢

4

1 回答 1

0

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

例子.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 不是 1 ,Content-Type则应写入 multipart/form-data并将其传递给 。For ... in

于 2019-03-30T15:30:41.760 回答