简体   繁体   中英

React-native upload Image as FormData

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);
        });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM