aboutsummaryrefslogtreecommitdiff
path: root/src/static/main.js
blob: b3ed57b9db6da83540f14f5f504e59e595d4e059 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
window.onload = function() {
    const form = document.querySelector('form')

    if (form !== null) {
        const submit = document.querySelector('input[type="submit"]')
        const loading = document.querySelector('.g-Loading')
        const error = document.querySelector('.g-Error')

        function showError(msg) {
            loading.style.display = 'none'
            submit.disabled = false
            error.innerText = msg
            error.style.display = 'block'
        }

        form.onsubmit = function(event) {
            event.preventDefault()

            loading.style.display = 'flex'
            submit.disabled = true
            error.style.display = 'none'

            const key = document.querySelector('input[name="key"]').value
            const expiration = document.querySelector('select[name="expiration"]').value
            const file = document.querySelector('input[name="file"]').files[0]
            const filename = file.name.replace(/[^0-9a-zA-Z\.]/gi, '-')

            // Wait a bit to prevent showing the loader too briefly
            setTimeout(function() {
                const xhr = new XMLHttpRequest()
                xhr.open('POST', '/upload', true)
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        window.location = `/share/${xhr.responseText}`
                    } else {
                        showError(`Error uploading: ${xhr.status}`)
                    }
                }
                xhr.onerror = function () {
                    showError('Upload error')
                }
                xhr.setRequestHeader('X-FileName', filename)
                xhr.setRequestHeader('X-Expiration', expiration)
                xhr.setRequestHeader('X-Key', key)
                xhr.send(file)
            }, 500)
        }
    }
}