SanctuaryCommander/static/script.js

58 lines
1.8 KiB
JavaScript

function updatePercentage(input_percent, progressBarContainerID, progressBarID) {
const clampedPercentage = Math.min(100, Math.max(0, input_percent))
const progressBar = document.getElementById(progressBarID)
const progressContainer = document.getElementById(progressBarContainerID)
progressBar.style.width = `${clampedPercentage}%`
progressContainer.setAttribute('aria-valuenow', clampedPercentage)
progressBar.textContent = `${clampedPercentage}%`
}
function uploadFiles(submitButtonID, fileInputID, progressBarContainerID, progressBarID, targetEndpoint, otherData) {
const submitButton = document.getElementById(submitButtonID)
submitButton.disabled = true
const files = document.getElementById(fileInputID).files
if (!files[0]) {
alert('Please select at least one file')
submitButton.disabled = false
return
}
const formData = new FormData()
for(var i = 0; i < files.length; i++) {
formData.append("files[]", files[i])
}
for(const key in otherData) {
formData.append(key, otherData[key])
}
var xhr = new XMLHttpRequest()
xhr.open("POST", targetEndpoint)
xhr.onload = function() {
if (xhr.status === 200) {
window.location.href = "/"
} else {
alert("Something went wrong during the upload, please try again later")
submitButton.disabled = false
}
}
xhr.upload.onprogress = function(event) {
if(event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100
updatePercentage(percentComplete, progressBarContainerID, progressBarID)
}
}
xhr.onerror = function() {
alert("An error occurred, please try again later")
submitButton.disabled = false
}
xhr.send(formData)
}