如何在 react-native 中使用 FormData? [英] How to use FormData in react-native?

查看:112
本文介绍了如何在 react-native 中使用 FormData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚学会使用 js 和 react-native.我不能使用 FormData 它总是显示不受支持的 bodyinit 类型.我想发送文本而不是 JSON.stringify.谁能帮我?谢谢!

Hi just learn to use js and react-native. I cant use FormData it always shows unsupported bodyinit type. I want to send text rather then JSON.stringify. Can anyone help me? Thanks!

var data = new FormData()
data.append('haha', 'input')

fetch('http://www.mywebsite.com/search.php', { 
  method: 'post',
  body: data
})
.then((response) => response.json())
.then((responseData) => {
  console.log('Fetch Success==================');
  console.log(responseData);

  var tempMarker = [];
  for (var p in responseData) {
   tempMarker.push({
    latitude: responseData[p]['lat'],
    longitude: responseData[p]['lng'] 
   })
  }

  this.setState({
    marker: tempMarker
  });

})
.catch((error) => {
  console.warn(error);
})
.done();

推荐答案

这里是我的简单代码 FormData,带有 react-native 来发布带有字符串和图像的请求.

Here is my simple code FormData with react-native to post request with string and image.

我使用 react-native-image-picker 来捕捉/选择照片 react-native-image-picker

I have used react-native-image-picker to capture/select photo react-native-image-picker

let photo = { uri: source.uri}
let formdata = new FormData();

formdata.append("product[name]", 'test')
formdata.append("product[price]", 10)
formdata.append("product[category_ids][]", 2)
formdata.append("product[description]", '12dsadadsa')
formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'image/jpeg'})

注意您可以将 image/jpeg 更改为其他内容类型.您可以从图片选择器响应中获取内容类型.

NOTE you can change image/jpeg to other content type. You can get content type from image picker response.

fetch('http://192.168.1.101:3000/products',{
  method: 'post',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  body: formdata
  }).then(response => {
    console.log("image uploaded")
  }).catch(err => {
    console.log(err)
  })  
});

这篇关于如何在 react-native 中使用 FormData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆