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…