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

后端 未结 3 1512
醉梦人生
醉梦人生 2021-02-09 14:21

\"reference

i want to post Form Data like that.

what should i prepare for sending ima

3条回答
  •  一向
    一向 (楼主)
    2021-02-09 14:56

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

提交回复
热议问题