2

Need to Post image as formData in React-Native

The Form Data:

------WebKitFormBoundary4df7ukBk3N8GDzOl Content-Disposition: form-data; name="selfieImage"; filename="600px-Google_Drive_logo.png" Content-Type: image/png

------WebKitFormBoundary4df7ukBk3N8GDzOl--

I need to recreate the above using react-native-image-picker, this is my code:

Image Picker Code:

ImagePicker.showImagePicker(options, (response) => {
        console.log('Response = ', 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 {
            formData = new FormData();
            formData.append("selfieImage", {
                name: 'selfieImage', 
                filename: response.uri
            })
            console.log(formData)

        //   this.setState({
        //     photo: formData,
        //   });
        }
      });

Axios Post Code:

 await axios({
        method: 'post',
        url: `${'{url}/home-security/image/selfie/' + this.state.newId}`,
        data: formData,
        config: { headers: {
            'Content-Type': 'multipart/form-data',
        }}
        })
        .then(function (response) {
            //handle success
            console.log(response);
        })
        .catch(function (response) {
            //handle error
            console.log(response);
        });
WilTree
  • 130
  • 1
  • 2
  • 12

1 Answers1

3

The method i know is to convert the image to base64 string and pass it through axios. but it's better to use a cloud service like AWS S3 to upload the image and send the image URL.

Naveed Sheriffdeen
  • 940
  • 6
  • 18
  • 37