Home > Software design >  React Native upload image
React Native upload image

Time:10-26

I'm trying to upload an image in react native to my server the backend works fine and in postman it also uploads the image but when I try to do it in the app it doesn't work does anyone know what's missing here and how I can implement the request exactly like this? I've already looked at tasuende docs but I just can't figure it out please help

PS: im using Axios

  const UploadImage = async () => {
if (!uri) {
  Alert.alert('No Image Uri');
}
const response = await myApi.postForm('/api/profile/avatar', {
  image: uri,
  
}).catch(function (error) {
  if (error.response) {
    console.log(error.response.data);
  } else if (error.request) {
    Alert.alert(error.request);
  } else {
    Alert.alert('Error', error.message);
  }
  return;
});

if (response){
  if (response.data.message){
    navigation.navigate('hi', {name: name});
  }
}    
};

 const pickImage = async () => {
const result = await launchImageLibrary();
if (result.assets[0].uri) {
  setUri(result.assets[0].uri);
}

};

CodePudding user response:

i think that you're performing the request wrong, try this instead :

Note : change the pickImage function so that the setUri takes (result.assets[0]) instead of (result.assets[0].uri)

const formBody = new FormData();
    formBody.append('image', {
        uri: uri.uri,
        name: uri.name,
        type: uri.type,
    });

then instead of passing { image : uri } next to url try to passe this : { body: formBody }

  • Related