Skip to content

Instantly share code, notes, and snippets.

@abennouna
Last active July 23, 2017 08:24
Show Gist options
  • Save abennouna/bd3865bcfccc5433975c553298eb433b to your computer and use it in GitHub Desktop.
Save abennouna/bd3865bcfccc5433975c553298eb433b to your computer and use it in GitHub Desktop.
File Upload using Angular
fileUpload(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
const xhr: XMLHttpRequest = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.response);
console.log('success');
} else {
console.log('error: ' + xhr.response);
}
}
};
xhr.open('POST', ApiUrl, true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Authorization', `Bearer ${localStorage.token}`);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
const formData = new FormData();
formData.append('photo', file, file.name);
xhr.send(formData);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment