React-Native分段照片上传在Android中不起作用

时间:2019-02-25 05:21:34

标签: android react-native fetch multipartform-data

我正在尝试使用react-native中的fetch multipart upload将图像文件发送/上传到我的后端服务,但是fetch multipart form数据上传不适用于android,但是我尝试了不同的示例。

图片上传多部分表单数据API基于php,并且适用于iOS react-native应用。

  

我正在使用react-native-photo-upload库拍摄图像。

storePicture(PicturePath:string) {
console.warn(PicturePath);
if (PicturePath) {
  const apiUrl = `${Constants.APIHOST}updateprofileimage.php`;
  // Create the form data object
  var data = new FormData();
  data.append('profileimage', { uri:PicturePath, name: 'profileimage.jpg', type: 'image/jpg/jpeg' });
  data.append('accesstoken', this.state.user.sAccessToken);
  data.append('react-native', 1);

  // Create the config object for the POST // You typically have an OAuth2 token that you use for authentication
  const config = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data;' }, body: data };
  fetch(apiUrl, config)
  .then(responseData => { // Log the response form the server
    // Here we get what we sent to Postman back
    console.warn(`response:${responseData}`);
  })
  .catch(err => {
    console.warn(err);
  });
}}
  

这是我如何调用storePicture()函数的示例。

<PhotoUpload onResizedImageUri={
        avatar => {
          if (avatar) {
            this.storePicture(avatar.path);
          }
        }}
      >
        <Image source={{uri: this.state.user.sProfileImageUrl}} style={{resizeMode:"cover", marginTop:8.0, backgroundColor:'transparent', height:120.0, width:120, borderRadius:60.0, borderWidth:0.0, borderColor:'transparent'}}/>
      </PhotoUpload>

2 个答案:

答案 0 :(得分:0)

uploadProfileImage = async (image:var) => {
this.setState({
  loading: true
});
var RNFS = require('react-native-fs');
const path = Style.IS_IOS ? image.uri : image.path;
var fileName = path.split('/').pop();
var fileType = fileName.split('.').pop();
var filePath = Style.IS_IOS ? path : 'file://' + path;

const apiURL = `${Constants.APIHOST}updateprofileimage.php`;
const formData = new FormData();
formData.append('accesstoken', this.state.user.sAccessToken);
formData.append('reactnative', 1);
formData.append('profileimage', {
  uri:filePath,
  name: fileName,
  type: `image/${fileType}`,
});
try {
  const response = await fetch(apiURL, {
    body: formData,
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data',
      'Accept': 'application/json',
    },
  })
  const json = await response.json()
  this.handleUploadImageResponse(json);
} catch (err) {
  this.setState({
    loading: false
  },console.log('catch Error: '+ err));
}

}

  

我正在回答自己的问题,因为为了其他面临相同问题的用户,我没有找到任何有效答案。

请让我知道我是否可以改善答案/帖子,或者如果需要我的帮助。

答案 1 :(得分:0)

通过Multipart FormData将图像上传到API

uploadPicture = () => {
  console.log(
    "Image Upload urI = " + JSON.stringify(this.state.imageSourceUri.uri)
  );
  this.setState({ loading: true });

  const form = new FormData();
  form.append("fileToUpload", {
    uri: this.state.imageSourceUri.uri,
    type: "image/jpg",
    name: "12334"
  });
  fetch("http://119.82.97.221/HPBSProjectApi2/api/HPBS/PostFormData", {
    method: "post",
    body: form
  })
    .then(response => response.json())
    .then(response => {
      console.log("response = " + response);
      this.setState({
        loading: false
      });
    });
};