Created
January 29, 2020 15:54
-
-
Save bpdarlyn/3d29d2065d45452bb5a0af5c43b0d379 to your computer and use it in GitHub Desktop.
Send Form Data with axios and file attachments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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