Skip to content

Instantly share code, notes, and snippets.

@bpdarlyn
Created January 29, 2020 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bpdarlyn/3d29d2065d45452bb5a0af5c43b0d379 to your computer and use it in GitHub Desktop.
Save bpdarlyn/3d29d2065d45452bb5a0af5c43b0d379 to your computer and use it in GitHub Desktop.
Send Form Data with axios and file attachments
# Create Form Data
const options = {
title: 'Selecciona tu Foto de Perfil',
};
_changeProfilePicture = () => {
ImagePicker.showImagePicker(options, 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 {
if (response.uri) {
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
image: {
name: response.fileName,
type: response.type,
uri: response.uri,
data: `data:${response.type};base64,${response.data}`,
},
});
}
console.log('Change Profile Picture');
console.log(this.state.image);
}
});
};
createFormData = (photo, body) => {
const data = new FormData();
data.append('image', photo);
Object.keys(body).forEach(key => {
data.append(key, body[key]);
});
return data;
};
# my body send to function createFormData
prepareData = () => {
{
first_name: this.state.first_name,
last_name: this.state.last_name,
phone: this.state.phone,
email: this.state.email,
};
let formData = this.createFormData(this.state.image, userInfo);
}
postToAxios = (infoData) => {
const {token_key} = state().session.user;
axios
.post(routes.UPDATE_PROFILE, userInfo, {
headers: {
'Client-Token': token_key,
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
if (res.status === 200) {
const {type, msg, payload} = res.data;
if (type === 'SUCCESSFULLY') {
dispatch(updateProfileSuccessfully(payload));
} else {
dispatch(updateProfileError('ERROR EN EL SERVIDOR', msg));
}
} else {
dispatch(
updateProfileError(
'ERROR EN EL SERVIDOR',
'Ocurrió un problema procesando tu solicitud',
),
);
}
})
.catch(error => {
console.log('Something was wrong on Profile Update :' + error);
console.log(error.response);
console.log(error.body);
dispatch(updateProfileError('ERROR EN EL SERVIDOR', error.message));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment