32 lines
762 B
TypeScript
Raw Permalink Normal View History

2019-11-18 02:04:13 +00:00
export default 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) => {
2019-11-17 09:25:14 +00:00
const xhr = new XMLHttpRequest()
2018-04-16 19:41:05 +00:00
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) {
2021-11-23 06:47:25 +00:00
for(const key of Object.keys(options.headers)) {
2019-04-19 13:12:33 +00:00
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
})
}