如何在react-native中使用fetch发布multipart/formdata?

jeh*_*hoi 5 fetch react-native react-native-android

参考图像:邮递员表格

我想发布这样的表单数据.

我应该准备什么来发送图像文件数据?

我有Uri,类型,文件名,大小.

然后将使用fetch for it.

标题中的内容类型是'multipart/formdata'

谢谢你的帮助

Mik*_*yan 12

你应该有一个上传功能,它应该是这样的:

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;
          });
      });
}
Run Code Online (Sandbox Code Playgroud)

你用这种方式调用它,发送图像blob路径:

this.upload('http://exampleurl.com/someApiCall', {
  file: {
    uri: image.path,
    type: image.mime,
    name: image.name,
  }
}).then(r => {
  //do something with `r`
});
Run Code Online (Sandbox Code Playgroud)