【问题标题】:How to post multipart/formdata using fetch in react-native?如何在 react-native 中使用 fetch 发布 multipart/formdata?
【发布时间】:2018-09-12 12:20:25
【问题描述】:

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

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

我有 Uri、类型、文件名、大小。

然后将使用 fetch 。

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

感谢帮助

【问题讨论】:

  • 我正在尝试做同样的事情。运气好吗?
  • 抱歉回复晚了,我的解决方案只是把它和其他表单数据放在一起 postData.append('webmailAttachment',{ uri:res.uri, type:res.type, name:res.文件名 });
  • 谁能看看这个doubt给我一些建议

标签: react-native fetch react-native-android


【解决方案1】:

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

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

你这样称呼它,发送图像 blob 路径:

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

【讨论】:

  • 您应该在fetch 调用中添加await 以简化sn-p。换句话说,没有理由将函数标记为“异步”。
【解决方案2】:

反应原生代码

fetch("url" ,{

    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },

    method:'POST',

    body: JSON.stringify(this.state.imageholder)

}).catch(function(error) {

console.log('There has been a problem with your fetch operation: ' + error.message);

throw error;

});

Spring 启动代码

 @PostMapping(value="/",consumes = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<?> saveCustomerOrder(@RequestBody String[] file) throws SerialException, SQLException {

    TestImg imgObj=null;

    for (String img : file) {
        imgObj=new TestImg();
        byte[] decodedByte = Base64.getDecoder().decode(img);
        Blob b = new SerialBlob(decodedByte);
        imgObj.setImg(b);
        testRepo.save(imgObj);

    }

【讨论】:

    【解决方案3】:

    您需要创建FormData 的实例并将其作为要获取的主体传递,如下所示:

    const data = new FormData()
    data.append("something", something)
    
    fetch(url, { method: 'POST', body: form })
    

    【讨论】:

    • 他们需要 Content-Type: multipart/form-data;边界=----WebKitFormBoundary7MA 我应该为边界添加一些特定的代码吗??
    猜你喜欢
    • 2020-05-01
    • 2016-06-17
    • 2018-03-28
    • 2015-12-03
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    相关资源
    最近更新 更多