React Native upload image network error

Asked

Viewed 285 times

-1

I’m having a problem uploading images using React Native, when I select the image the application returns a network error.

My code:

  state = {
avatarSource: null,
isUploading: false

}

  selectImage = async () => {
    ImagePicker.showImagePicker({ title: 'Selecionar Foto',
    noData: true,
    mediaType: 'photo',
    takePhotoButtonTitle: 'Tirar foto',
    chooseFromLibraryButtonTitle: 'Escolher da Galeria' },
    (response) => {


  if (response.didCancel) {
    Alert.alert('Error','User cancelled image picker');
  } else if (response.error) {
    Alert.alert('Error','ImagePicker Error: ');
  } else if (response.customButton) {
    Alert.alert('Error','User tapped custom button: ');
  } else {
    this.uploadImage(response.uri);
  }
});

}

  uploadImage = async (image_uri) => {
    this.setState({ isUploading: true });
    let base_url = 'http://192.168.0.101:80/config/upload.php/';
    let uploadData = new FormData();
    uploadData.append('submit', 'ok');
    uploadData.append('file', { type: 'image/jpg', uri: image_uri, name: 'uploadimgtmp.jpg' });
    fetch(base_url, {
      method: 'post',
      body: uploadData
    }).then(response => response.json())
      .then(response => {
        if (response.status) {
          this.setState({ isUploading: false, avatarSource: base_url + response.image });
        } else {
          this.setState({ isUploading: false });
          Alert.alert('error', response.message);
        }
      }).catch(() => {
        this.setState({ isUploading: false });
        Alert.alert('Error', 'Erro na rede');
      })
  }

  render() {
const { navigate } = this.props.navigation;
return (
  <View style={styles.container}>
    <View style={styles.txtbg}>
      <Text style={styles.headertxt}>Quase lá!</Text>
    </View>
    <Text style={styles.headertxt2}>ADICIONAR  FOTO  DE  PERFIL</Text>
    {this.state.avatarSource && <Image style={{ borderWidth: 2, borderColor: '#fff', width: 170, height: 170, resizeMode: 'cover', borderRadius: 120 }} source={{ uri: this.state.avatarSource }} />}
    <TouchableOpacity onPress={this.selectImage} style={styles.loginFoto}>
      <Text style={styles.loginText}>ESCOLHER FOTO</Text>
    </TouchableOpacity>
    {this.state.isUploading && <ActivityIndicator size="small" color="#fff" />}
    <TouchableOpacity style={styles.loginBtn}>
      <Text style={styles.loginText}>CONTINUAR  <Icon name="angle-right" size={16} /><Icon name="angle-right" size={16} /></Text>
    </TouchableOpacity>
    <TouchableOpacity>
      <Text style={styles.loginText2}>PULAR</Text>
    </TouchableOpacity>
  </View>
);

}

This is React Native code, it communicates with a server PHP, that is currently running on LOCALHOST.

The code PHP is as follows:

$data = array('status'=> false);

if (isset($_POST['submit'])) {
    $target_file = basename($_FILES['file']['name']);
    $file_type = pathinfo($target_file, PATHINFO_EXTENSION);
    $is_image = getimagesize($_FILES['file']['tmp_name']);

if ($is_image !== false) {
    $data['image'] = tine() . '.' . $file_type;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $data['image'])) {
        $data['status'] = true;
    }else{
    $data['message'] = 'Falha ao carregar foto';
    }
}else{
    $data['message'] = 'Arquivo invalido!';
}

}

header('Access-Control-Allow-Origin *');
header('Content-type:application/json');
echo json_encode($data);

When I select the image it immediately falls into the network error:

 .catch(() => {
        this.setState({ isUploading: false });
        Alert.alert('Error', 'Erro na rede');
      })

I am running the application on my own Smartphone that communicates with my machine. I think the problem really is in the code , after all I have other forms that communicate well with the server and my local server (WAMPSERVER) is configured to allow uploads regardless of size!

Versions used:

  SDKs:
    Android SDK:
      API Levels: 27, 28
      Build Tools: 27.0.3, 28.0.3
  npmPackages:
    react: 16.9.0 => 16.9.0
    react-native: 0.61.5 => 0.61.5

1 answer

0


By the description of your error, the problem may be in your backend, there may have been some problem with the answer, so it fell in the "catch". One way to try to identify the problem is to print the error message on the console, for that, you would have to make the following adjustment in the send image function

 uploadImage = async (image_uri) => {
    this.setState({ isUploading: true });
    let base_url = 'http://192.168.0.101:80/config/upload.php/';
    let uploadData = new FormData();
    uploadData.append('submit', 'ok');
    uploadData.append('file', { type: 'image/jpg', uri: image_uri, name: 'uploadimgtmp.jpg' });

    console.log(uploadData); //Para conferir os dados do formulario

    fetch(base_url, {
      method: 'post',
      body: uploadData
    }).then(response => response.json())
      .then(response => {
        if (response.status) {
          this.setState({ isUploading: false, avatarSource: base_url + response.image });
        } else {
          this.setState({ isUploading: false });
          Alert.alert('error', response.message);
        }
      }) .catch(error => {
        console.log("Erro", error); //Para ver o erro que foi recebido
        this.setState({ isUploading: false });
        Alert.alert('Error', 'Erro na rede');
      });
  }

I recommend you to test direct image upload to your backend using Postman. Here’s a tutorial explaining how to do this:

https://www.roytuts.com/how-to-call-file-upload-rest-api-using-postman/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.