Improved file upload

This commit is contained in:
Eduard Urbach 2018-04-16 21:41:05 +02:00
parent 889a9700ad
commit bb15daae6b
2 changed files with 45 additions and 15 deletions

View File

@ -1,5 +1,6 @@
import AnimeNotifier from "../AnimeNotifier" import AnimeNotifier from "../AnimeNotifier"
import StatusMessage from "../StatusMessage" import StatusMessage from "../StatusMessage"
import { fetchWithProgress } from "../Utils/fetchWithProgress"
// Select file // Select file
export function selectFile(arn: AnimeNotifier, button: HTMLButtonElement) { export function selectFile(arn: AnimeNotifier, button: HTMLButtonElement) {
@ -54,29 +55,39 @@ function uploadFile(file: File, fileType: string, endpoint: string, arn: AnimeNo
let reader = new FileReader() let reader = new FileReader()
reader.onloadend = async () => { reader.onloadend = async () => {
arn.statusMessage.showInfo(`Uploading ${fileType}...`, 60000) let megaBytes = reader.result.byteLength / 1024 / 1024
arn.statusMessage.showInfo(`Uploading ${fileType}...${megaBytes.toFixed(1)} MB`, -1)
let response = await fetch(endpoint, { try {
method: "POST", let responseText = await fetchWithProgress(endpoint, {
credentials: "include", method: "POST",
headers: { credentials: "include",
"Content-Type": "application/octet-stream" headers: {
}, "Content-Type": "application/octet-stream"
body: reader.result },
}) body: reader.result
}, e => {
if(!e.lengthComputable) {
return
}
if(endpoint === "/api/upload/avatar") { let progress = e.loaded / e.total * 100
let newURL = await response.text() arn.statusMessage.showInfo(`Uploading ${fileType}...${progress.toFixed(1)}%`, -1)
updateSideBarAvatar(newURL) })
}
if(response.ok) {
arn.statusMessage.showInfo(`Successfully uploaded your new ${fileType}.`) arn.statusMessage.showInfo(`Successfully uploaded your new ${fileType}.`)
} else {
if(endpoint === "/api/upload/avatar") {
// We received the new avatar URL
updateSideBarAvatar(responseText)
}
} catch(err) {
arn.statusMessage.showError(`Failed uploading your new ${fileType}.`) arn.statusMessage.showError(`Failed uploading your new ${fileType}.`)
console.error(err)
} }
} }
arn.statusMessage.showInfo(`Reading ${fileType} from disk...`, -1)
reader.readAsArrayBuffer(file) reader.readAsArrayBuffer(file)
} }

View File

@ -0,0 +1,19 @@
export function fetchWithProgress(url, opts: RequestInit, onProgress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null): Promise<string> {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(opts.method || "GET", url)
for(let k in opts.headers || {}) {
xhr.setRequestHeader(k, opts.headers[k])
}
xhr.onload = e => resolve(xhr.responseText)
xhr.onerror = reject
if(xhr.upload && onProgress) {
xhr.upload.onprogress = onProgress
}
xhr.send(opts.body)
})
}