Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post multipart/formdata using fetch in react-native?

reference Image: Postman form

i want to post Form Data like that.

what should i prepare for sending image file data?

i have Uri, type, filename, size.

then will use fetch for it.

Content-type in header is 'multipart/formdata'

thanks for helping

like image 940
jehee choi Avatar asked Apr 03 '18 08:04

jehee choi


People also ask

How do you use fetch in React Native?

In React Native, you can request data from an API over the network using the fetch() method. The syntax is simple as follows: fetch('https://examples.com/data.json'); We simply pass the URL to the fetch method to make a request.


1 Answers

You should have an upload function, which should look like this:

upload(url, data) {
  let options = {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    method: 'POST'
  };

  options.body = new FormData();
  for (let key in data) {
    options.body.append(key, data[key]);
  }

  return fetch(requestUrl, options)
      .then(response => {
        return response.json()
          .then(responseJson => {
            //You put some checks here
            return responseJson;
          });
      });
}

And you call it this way, sending the image blob path:

this.upload('http://exampleurl.com/someApiCall', {
  file: {
    uri: image.path,
    type: image.mime,
    name: image.name,
  }
}).then(r => {
  //do something with `r`
});
like image 64
Mikayel Saghyan Avatar answered Sep 18 '22 14:09

Mikayel Saghyan