summaryrefslogtreecommitdiff
path: root/templates/scripts/simple-upload.js
blob: c3a0defb606530f12339d614b2bb5477693d65d8 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');
const form = document.getElementById('uploadForm');
const result = document.getElementById('result');
const uploadBtn = document.getElementById('uploadBtn');

fileInput.addEventListener('change', (e) => {
  const files = e.target.files;
  if (files.length > 0) {
    const names = Array.from(files).map(f => f.name).join(', ');
    fileInfo.textContent = `Selected: ${files.length} file(s) - ${names}`;
  }
});

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const files = fileInput.files;

  if (files.length === 0) {
    showResult('Please select at least one file', 'error');
    return;
  }

  uploadBtn.disabled = true;
  uploadBtn.textContent = 'Uploading...';

  const formData = new FormData();
  for (let i = 0; i < files.length; i++) {
    formData.append('files', files[i]);
  }

  try {
    const response = await fetch('/upload', {
      method: 'POST',
      body: formData
    });

    const data = await response.json();

    if (response.ok) {
      const links = data.files.map(f =>
        `<a href="/download/${f}" target="_blank" style="display: block; margin: 5px 0;">${window.location.origin}/download/${f}</a>`
      ).join('');
      showResult('Upload successful!<br>' + links, 'success');
      form.reset();
      fileInfo.textContent = 'Max size: {{max-size}}MB per file';
    } else {
      showResult('Error: ' + data.error, 'error');
    }
  } catch (error) {
    showResult('Upload failed: ' + error.message, 'error');
  } finally {
    uploadBtn.disabled = false;
    uploadBtn.textContent = 'Upload';
  }
});

function showResult(message, type) {
  result.innerHTML = message;
  result.style.display = 'block';
  if (type === 'success') {
    result.style.background = '#d4edda';
    result.style.color = '#155724';
    result.style.border = '1px solid #c3e6cb';
  } else {
    result.style.background = '#f8d7da';
    result.style.color = '#721c24';
    result.style.border = '1px solid #f5c6cb';
  }
}