Ad

How To Upload Image To Server With Image Picker React Native

- 1 answer

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

Ad

Answer

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.push('userId', dataProfile.id)
formData.push('pictures', imageProfile)

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
    });
};
Ad
source: stackoverflow.com
Ad