32 lines
737 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()
xhr.onload = () => {
if(xhr.status >= 400) {
return reject(xhr.responseText)
}
resolve(xhr.responseText)
}
2018-04-17 12:41:31 +00:00
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
2019-04-19 13:12:33 +00:00
if(options.headers) {
for(let key in options.headers) {
xhr.setRequestHeader(key, options.headers[key])
}
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
})
}