Last active
May 8, 2017 06:41
-
-
Save giscafer/b8e974755324ccf8b448307d2e38c726 to your computer and use it in GitHub Desktop.
XMLHttpRequest + FormData图片上传
This file contains hidden or 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
/** | |
* let formData = new FormData(); | |
* for (let i = 0; i < this.files.length; i++) { | |
formData.append("file", this.files[i], this.files[i].name); | |
} | |
*/ | |
uploadPic(formData){ | |
let jwt = localStorage["jwt"]; | |
/*let headers = new Headers({ | |
'Content-Type': 'multipart/form-data', | |
'Authorization': "Bearer " + jwt | |
}); | |
let options = new RequestOptions({headers: headers}); | |
return this.http.post(this.uploadUrl, formData, options) | |
.toPromise() | |
.then(this.extractData) | |
.catch(this.handleError);*/ | |
let xhr = new XMLHttpRequest(); | |
return new Promise((resolve, reject) => { | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState == 4) { | |
if (xhr.status >= 200 && xhr.status < 300) | |
resolve({xhr: xhr, formData: formData}); | |
else | |
reject({xhr: xhr, formData: formData}); | |
} | |
}; | |
xhr.open('POST', this.uploadUrl, true); | |
xhr.setRequestHeader("Authorization", "Bearer " + jwt); | |
xhr.send(formData); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment