How to upload files image on React Native (Android)

Viewed 24

I am trying to upload file image to server from React Native, But I get

Network request failed

however

this code can work on IOS but can not work on ANDROID.

const pickImage = async () => {
let files = await ImagePicker.launchImageLibraryAsync({
  mediaTypes: ImagePicker.MediaTypeOptions.Images,
  // allowsEditing: true,
  // aspect: [4, 3],
  quality: 1,
});

if (!files.cancelled) {
  uploadImage(files);
}


const uploadImage = async (image) => {
let formData = new FormData();
formData.append("files", {
  type: image.uri.split(".").pop(),
  uri: image.uri,
  name: image.uri.split("/").pop(),
});
var requestOptions = {
  method: "POST",
  body: formData,
  headers: {
    "Content-Type": "multipart/form-data",
    Accept: "application/json",
  },
};
fetch(
  "http://192.168.1.53:3100/ApiUploadProfileImage",
  requestOptions
).then(async (res) => {
  let returnText = await res.text();
  try {
    httpClient
      .post(`/Profile/UploadImage`, { url: returnText, userId: userId })
      .then((response) => {
        if (response.data.result == "Upload Suscess") {
          profile.ProfilesImage = returnText;
          console.log("Suscess : ", returnText);
        }
      });
  } catch (error) {
    console.log(error);
  }
});

And the error msg: XlE2T.png

Please help.

1 Answers

try this

    import ImagePicker from "react-native-image-picker";
    
    selectProfileImage = async () => {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          ImagePicker.showImagePicker(options, async (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 {
              const source = response.uri;
              await this.uploadImage(
                response.uri,
                response.fileName,
                response.type
              );
             }
          });
        } else {
          console.log("Camera permission denied");
        }
      };
    
      uploadImage = async (uri, name, type) => {
        const data = new FormData();
        data.append("image", {
          uri: uri,
          type: type,
          name: name,
        });
    
        await Axios.post(BASE_URL + "editProfileImage", data, {
          headers: {
            Accept: ACCEPT_HEADER,
            Authorization: "Bearer " + this.state.token,
         
          },
        })
          .then((res) => {
             console.log("-----upload ", res.data);
         })
          .catch((err) => {
            console.log(JSON.stringify(err, null, 2));
          });
      };

 render() {
    return (
      <View style={{ flex: 1, backgroundColor: colors.white }}>
   <TouchableOpacity
              style={{
                height: 200,
                width: 200,
                alignSelf: "center",
                justifyContent: "center",
                alignItems: "center",
                marginTop: "10%",
                borderWidth: 0.5,
                borderColor: colors.lightblue,
                borderRadius: 5,
                borderRadius: 100,
              }}
              onPress={() => this.selectProfileImage()}
            >
              <Image
                source={
                  this.state.ProfileImage === ""
                    ? require("../../Image/user.png")
                    : { uri: this.state.ProfileImage }
                }
                style={{
                  height: 195,
                  width: 195,
                  borderWidth: 1,
                  borderRadius: 100,
                }}
              />

              <TouchableOpacity
                onPress={() => this.selectProfileImage()}
                style={{
                  height: 40,
                  width: 40,
                  backgroundColor: colors.lightblue,
                  borderRadius: 100,
                  justifyContent: "center",
                  alignItems: "center",
                  position: "absolute",
                  bottom: 0,
                  right: 15,
                }}
              >
                <FontAwesome5Icon name="pen" size={22} color={colors.white} />
              </TouchableOpacity>
            </TouchableOpacity>
</View>
)
}
Related