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



我正在使用REECT本机上的移动应用程序工作,并在iOS上发布图像不起作用。我已经将代码连接到请求Bin,设置Info.plist以允许非HTTPS URL和其他帖子请求正在工作(例如登录)。对于图像,我得到的只是一个空白的主体。这是发布图像的代码:

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-nimimage-picker将其获取并将其存储在变量"徽标"下。这也是该代码

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

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

    let url     = "",
        headers = "",
        method  = "POST",
        body    = new FormData(),
        uri     = "URI of the picked image.";
    body.append("photo", {
            name: "Just a name",
            uri : Platform.OS === "android" ? uri : uri.replace("file://", "")
        }
    );
    fetch(url, method, headers, body)
        .then(function (response) {
        })
        .catch(function (error) {
        });
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)
        });
}

如果有人在iOS中使用获取问题,请查看react-native-file-upoad,我发现它在图像上传和常规帖子中都非常有帮助。

相关内容

  • 没有找到相关文章

最新更新