【问题标题】:How can I format the structure of my formData object to match what the backend expects?如何格式化我的 formData 对象的结构以匹配后端的期望?
【发布时间】:2019-03-30 03:41:06
【问题描述】:

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

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    使用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)
    
    

    如上例所示,Content-Type 应该写成 multipart/form-data,如果 Stringdata 不为 1,则将其传递给 For ... in

    【讨论】:

    • 谢谢!问题原来是错字。我拼写了“标题”而不是“标题”。 掌心
    • 我很高兴事情解决了。如果我的答案是正确的,你会选择我的答案吗?
    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 2019-02-28
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    相关资源
    最近更新 更多