0

I am using formData to POST an image I uploaded via ImagePicker. I am sending the parameters like so:

  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
    },
  });
  };

This doesn't seem to work, as I am getting a very generic NoMethodError (undefined methodbuild' for nil:NilClass):` error.

How can I POST my parameters in the correct way given that the image parameter is an image and the description parameter is a string?

Thanks

Ozge Cokyasar
  • 301
  • 1
  • 4
  • 16

1 Answers1

0

Content-Type must be different when using Formdata.

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)

As shown in the example above, Content-Type should write multipart/form-data and pass it over to For ... in if Stringdata is not one.

hong developer
  • 13,291
  • 4
  • 38
  • 68