Improved file upload
This commit is contained in:
parent
889a9700ad
commit
bb15daae6b
@ -1,5 +1,6 @@
|
||||
import AnimeNotifier from "../AnimeNotifier"
|
||||
import StatusMessage from "../StatusMessage"
|
||||
import { fetchWithProgress } from "../Utils/fetchWithProgress"
|
||||
|
||||
// Select file
|
||||
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()
|
||||
|
||||
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 {
|
||||
let responseText = await fetchWithProgress(endpoint, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: {
|
||||
"Content-Type": "application/octet-stream"
|
||||
},
|
||||
body: reader.result
|
||||
}, e => {
|
||||
if(!e.lengthComputable) {
|
||||
return
|
||||
}
|
||||
|
||||
let progress = e.loaded / e.total * 100
|
||||
arn.statusMessage.showInfo(`Uploading ${fileType}...${progress.toFixed(1)}%`, -1)
|
||||
})
|
||||
|
||||
if(endpoint === "/api/upload/avatar") {
|
||||
let newURL = await response.text()
|
||||
updateSideBarAvatar(newURL)
|
||||
}
|
||||
|
||||
if(response.ok) {
|
||||
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}.`)
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
arn.statusMessage.showInfo(`Reading ${fileType} from disk...`, -1)
|
||||
reader.readAsArrayBuffer(file)
|
||||
}
|
||||
|
||||
|
19
scripts/Utils/fetchWithProgress.ts
Normal file
19
scripts/Utils/fetchWithProgress.ts
Normal 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)
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user