24 lines
627 B
TypeScript
Raw Normal View History

2018-04-17 12:41:31 +00:00
export function uploadWithProgress(url, options: RequestInit, onProgress: ((ev: ProgressEvent) => any) | null): Promise<string> {
2018-04-16 19:41:05 +00:00
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
2018-04-17 12:41:31 +00:00
xhr.onload = e => resolve(xhr.responseText)
xhr.onerror = reject
2018-04-16 19:41:05 +00:00
2018-04-17 11:16:53 +00:00
if(onProgress && xhr.upload) {
2018-04-17 12:41:31 +00:00
xhr.upload.onprogress = onProgress
xhr.upload.onerror = reject
} else {
console.error("Could not attach progress event listener")
2018-04-17 11:16:53 +00:00
}
2018-04-16 19:41:05 +00:00
2018-04-17 11:35:17 +00:00
xhr.open(options.method || "GET", url, true)
2018-04-17 11:07:42 +00:00
2018-04-17 11:16:53 +00:00
for(let k in options.headers || {}) {
xhr.setRequestHeader(k, options.headers[k])
2018-04-16 19:41:05 +00:00
}
2018-04-16 19:41:37 +00:00
xhr.send(options.body)
2018-04-16 19:41:05 +00:00
})
}