使用fetch上传图像在React Native(iOS)中不起作用

时间:2017-12-15 05:19:54

标签: react-native react-native-ios fetch-api

我正在使用React Native开发移动应用,在iOS上发布图片无效。我已将我的代码连接到requestbin,设置info.plist以允许非https网址和其他帖子请求正在运行(例如登录)。对于图像,我得到的只是请求的空白主体。这是发布图像的代码:

uploadImage = () => {
const data = new FormData();
data.append('photo', {
  uri: this.state.logo.uri,
  name: 'logo'
});
fetch([requestbin url here], {
  method: 'post',
  body: data
}).then(res => {
  console.log(res);
});

对于图像,我使用react-native-image-picker来获取它并将其存储在变量'logo'下的状态。这也是代码

 handleNewImage = () => {
var options = {
  title: 'Choose new company logo',
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};

showImagePicker(options, response => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled image picker');
  } else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  } else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  } else {
    let source = { uri: response.uri };

    // You can also display the image using data:
    // let source = { uri: 'data:image/jpeg;base64,' + response.data };

    this.setState({
      logo: source
    });
  }
});

3 个答案:

答案 0 :(得分:2)

请记住,您也应该传递名称键,如下所示:

/p

答案 1 :(得分:1)

function uploadProfilePicture(mImage) {

    var data = new FormData();
    data.append('theFile', { uri: mImage.uri, name: 'profile_photo.jpg', type: 'image/jpg' });

    fetch(AppConstant.BASE_URL + AppConstant.upload_media, {
        method: 'POST',
        body: data
    })
        .then((response) => response.json())
        .then((responseJson) => {

            var err = 'error_message' in responseJson ? true : false
            if (err) {
                alert(responseJson.error_message)

            } else {


                alert(JSON.stringify(responseJson))

            }

        })
        .catch((error) => {
            console.error(error);
            alert(error)
        });

}

答案 2 :(得分:-1)

如果有人在iOS中使用fetch有问题,请查看react-native-file-upload我发现它在图片上传和常规帖子中都非常有用。

相关问题