Last active
July 23, 2017 08:24
-
-
Save abennouna/bd3865bcfccc5433975c553298eb433b to your computer and use it in GitHub Desktop.
File Upload using Angular
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
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