65 lines
1.6 KiB
TypeScript
Raw Normal View History

2018-03-02 16:18:29 +00:00
import { AnimeNotifier } from "../AnimeNotifier"
// Select file
export function selectFile(arn: AnimeNotifier, button: HTMLButtonElement) {
let input = document.createElement("input")
let preview = document.getElementById(button.dataset.previewImageId) as HTMLImageElement
input.setAttribute("type", "file")
input.onchange = () => {
2018-03-02 20:42:34 +00:00
let file = input.files[0]
previewImage(file, preview)
2018-03-03 15:03:18 +00:00
uploadFile(file, "/api/upload/avatar", arn)
2018-03-02 16:18:29 +00:00
}
input.click()
}
// Preview image
2018-03-02 20:42:34 +00:00
function previewImage(file: File, preview: HTMLImageElement) {
2018-03-02 16:18:29 +00:00
let reader = new FileReader()
reader.onloadend = () => {
preview.classList.remove("hidden")
preview.src = reader.result
}
if(file) {
reader.readAsDataURL(file)
} else {
2018-03-02 20:42:34 +00:00
preview.classList.add("hidden")
2018-03-02 16:18:29 +00:00
}
}
2018-03-02 23:20:10 +00:00
// Upload file
2018-03-03 15:03:18 +00:00
function uploadFile(file: File, endpoint: string, arn: AnimeNotifier) {
2018-03-02 20:42:34 +00:00
let reader = new FileReader()
reader.onloadend = async () => {
2018-03-03 15:03:18 +00:00
arn.statusMessage.showInfo("Uploading avatar...")
let response = await fetch(endpoint, {
2018-03-02 20:42:34 +00:00
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/octet-stream"
},
body: reader.result
})
2018-03-03 15:03:18 +00:00
let newURL = await response.text()
let sidebar = document.getElementById("sidebar")
let userImage = sidebar.getElementsByClassName("user-image")[0] as HTMLImageElement
userImage.dataset.src = newURL
userImage["became visible"]()
2018-03-03 15:03:18 +00:00
if(response.ok) {
arn.statusMessage.showInfo("Successfully uploaded your new avatar.")
} else {
arn.statusMessage.showError("Failed uploading your new avatar.")
}
2018-03-02 20:42:34 +00:00
}
2018-03-02 16:18:29 +00:00
2018-03-02 23:04:54 +00:00
reader.readAsArrayBuffer(file)
2018-03-02 16:18:29 +00:00
}