Improved uploader

This commit is contained in:
Eduard Urbach 2018-04-17 13:01:51 +02:00
parent 8cb44131cf
commit d9ff1513b8
3 changed files with 24 additions and 17 deletions

View File

@ -1,6 +1,6 @@
import AnimeNotifier from "../AnimeNotifier" import AnimeNotifier from "../AnimeNotifier"
import StatusMessage from "../StatusMessage" import StatusMessage from "../StatusMessage"
import { fetchWithProgress } from "../Utils/fetchWithProgress" import { bytesHumanReadable, fetchWithProgress } from "../Utils"
// Select file // Select file
export function selectFile(arn: AnimeNotifier, button: HTMLButtonElement) { export function selectFile(arn: AnimeNotifier, button: HTMLButtonElement) {
@ -56,19 +56,13 @@ function uploadFile(file: File, fileType: string, endpoint: string, arn: AnimeNo
reader.onloadend = async () => { reader.onloadend = async () => {
let fileSize = reader.result.byteLength let fileSize = reader.result.byteLength
let unit = "bytes"
if(fileSize >= 1024) { if(fileSize === 0) {
fileSize /= 1024 arn.statusMessage.showError("File is empty")
unit = "KB" return
if(fileSize >= 1024) {
fileSize /= 1024
unit = "MB"
}
} }
arn.statusMessage.showInfo(`Uploading ${fileType}...${fileSize.toFixed(0)} ${unit}`, -1) arn.statusMessage.showInfo(`Preparing to upload ${fileType} (${bytesHumanReadable(fileSize)})`, -1)
try { try {
let responseText = await fetchWithProgress(endpoint, { let responseText = await fetchWithProgress(endpoint, {
@ -79,11 +73,7 @@ function uploadFile(file: File, fileType: string, endpoint: string, arn: AnimeNo
}, },
body: reader.result body: reader.result
}, e => { }, e => {
if(!e.lengthComputable) { let progress = e.loaded / (e.lengthComputable ? e.total : fileSize) * 100
return
}
let progress = e.loaded / e.total * 100
arn.statusMessage.showInfo(`Uploading ${fileType}...${progress.toFixed(1)}%`, -1) arn.statusMessage.showInfo(`Uploading ${fileType}...${progress.toFixed(1)}%`, -1)
}) })

View File

@ -0,0 +1,15 @@
export function bytesHumanReadable(fileSize: number): string {
let unit = "bytes"
if(fileSize >= 1024) {
fileSize /= 1024
unit = "KB"
if(fileSize >= 1024) {
fileSize /= 1024
unit = "MB"
}
}
return `${fileSize.toFixed(0)} ${unit}`
}

View File

@ -3,4 +3,6 @@ export * from "./delay"
export * from "./findAll" export * from "./findAll"
export * from "./plural" export * from "./plural"
export * from "./requestIdleCallback" export * from "./requestIdleCallback"
export * from "./swapElements" export * from "./swapElements"
export * from "./fetchWithProgress"
export * from "./bytesHumanReadable"