How to post image with expo camera?

#1

Hello, there. I’m building a react native apps and I’m using camera from expo for one of the feature, which is, changing profile picture. I tried some tutorial on the Internet but I got an error. Here is my code:

  _pickImage = async () => {
      const {
        status: cameraRollPerm
      } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (cameraRollPerm === 'granted') {
      let pickerResult = await ImagePicker.launchImageLibraryAsync({
        allowsEditing: true,
        aspect: [4, 3],
        base64: true,
      });

      this._handleImagePicked(pickerResult);
    }
  };

  _handleImagePicked = async (pickerResult) => {
    try {
      this.setState({
        uploading: true,
      });

      if (!pickerResult.cancelled) {
        const uri = this.state.user.pict;
        let apiUrl= `http://localhost/upload/`;
	      let uriParts = uri.split('.');
	      let fileType = uriParts[uriParts.length - 1];
	      let formData = new FormData();
	      formData.append('photo', {
		      uri,
	    	  name:`photo.${fileType}`,
		      type: `image/${fileType}`,
	      });
	      console.warn(formData);
        let upload = await fetch(apiUrl, {
            method: 'POST',
            headers: {
              Authorization: token,
              Accept: 'application/json',
              'Content-Type': 'multipart/form-data',
            },
            body: JSON.stringify({
                        	user_id: user_id,
                        	avatar: formData,
                        	username: this.state.user.username,
                        }),
          }).then(response=> response.json()).catch(error=>{
    		console.warn(error);
    	});
        this.setState({
          picture_profile: response.location,
        });
      }
  }
    catch (e) {
       console.warn({ upload });
       console.warn({ response });
      console.warn({ e });
      Alert.alert('Upload failed, sorry :('); // <---- I GOT THIS ERROR
    } finally {
      this.setState({
         uploading: false,
      });
    }
  };

When I tried to upload a picture from gallery, I got an error alert. I’m so confused and didn’t know how to do… can anyone please help me? Thank you so much…

#2

Can u provide ur Error console ?

#3

import { Image } from ‘react-native’;

Image View Code :-

       <View style={{ justifyContent: 'center', alignItems: 'center', marginTop: SCREEN_HEIGHT / 80 }}>
                <TouchableOpacity onPress={this._pickImage}>
                  <Image
                    source={this.state.image_uri
                      ?
                      { uri: `${this.state.image_uri}` }
                      :
                      Dummy_image}
    
                    style={{ backgroundColor: 'transparent', width: IMAGE_SIZE, height: IMAGE_SIZE, borderRadius: IMAGE_SIZE / 2 }}
                  />

                </TouchableOpacity>
              </View>
```Preformatted text


  //function for pic image from galary
  //first request and get permission from user then set profile pic
  _pickImage = async () => {
    const {
      status: cameraRollPerm
    } = await Permissions.askAsync(Permissions.CAMERA_ROLL);

    // only if user allows permission to camera roll
    if (cameraRollPerm === 'granted') {
      let pickerResult = await ImagePicker.launchImageLibraryAsync({
        allowsEditing: true,
        aspect: [4, 3],
      });

      //handle image uri
      this._handleImagePicked(pickerResult);
    }
  };

  // function for handle image uri
  //change the state uploading image true
  //if not uploading then only showing previous image and state is used by default
  _handleImagePicked = async pickerResult => {
    let uploadResponse;

    try {
      this.setState({
        uploading: true
      });
      console.log("pickerResult.uri :- " + pickerResult.uri)
      if (!pickerResult.cancelled) {
        // uploadResponse = await uploadImageAsync(pickerResult.uri);
        this.setState({
          //image: uploadResult.location,
          image_uri: pickerResult.uri
        });
        console.log('sending image')
        this._Calldetails_submit(pickerResult.uri)
      }
    } catch (exception) {
      console.log({ uploadResponse });
      // console.log({ uploadResult });
      console.log({ exception });
      alert('Upload failed, sorry :(');
    } finally {
      this.setState({
        uploading: false
      });
    }
  };


@hehe
let me know that it is helpful for you or not ?
good luck.
#4

thanks for your respond, this is the error message I got:

20%20PM

thank you so much! I’ll try this code and I’ll let you know if it’s working or not (i hope it is)

#6

oh no, I got the same error… while the uploadResponse only got {} @biplov14

#7

Error console ?

closed #8

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.