Home > OS >  How to upload image to server with image picker react native
How to upload image to server with image picker react native

Time:02-12

I want to upload image and upload to server. how can i get a file and can read in server?

const takePhotoFromLibraryProfile = () => {
    ImagePicker.openPicker({
      width: 200,
      height: 200,
      cropping: true,
    }).then(image => {
      setImageProfile(image.path);
    });
  };

and this my axios post

axios({
      crossDomain: true,
      method: 'post',
      url: 'url',
      data: {
        userId: dataProfile.id,
        pictures: imageProfile,
      },
      validateStatus: false,
    })
      .then((response, status) => {
        console.log(response);
        setSuccessModal(response.status);
      })
      .catch(function (error) {
        console.log(error);
        // need handling error
      });
  };

i got the respon and also false but in develop web can upload the image. Thank you

CodePudding user response:

To upload images to files to web servers, We cannot send it in the data property of Axios or fetch.

To Upload files or image, we have to convert the data into form data. And then we can send the form data to the webserver with the help of the Axios or fetch.

For Example:

const formData = new FormData()
formData.append('userId', dataProfile.id)
formData.append('pictures', {
    uri: user.profilePicture,
    type: 'image/jpeg',
    name: 'photo.jpg'
})

axios({
    method: 'post',
    url: 'url',
    data: formData,
  })
    .then((response, status) => {
      console.log(response);
      setSuccessModal(response.status);
    })
    .catch(function (error) {
      console.log(error);
      // need handling error
    });
};
  • Related