|
16 | 16 | form.appendChild(input)
|
17 | 17 | }
|
18 | 18 |
|
| 19 | + function waitForAllFiles(form) { |
| 20 | + if (window.uploading !== 0) { |
| 21 | + setTimeout(() => { |
| 22 | + waitForAllFiles(form) |
| 23 | + }, 100) |
| 24 | + } else { |
| 25 | + form.submit() |
| 26 | + } |
| 27 | + } |
| 28 | + |
19 | 29 | function request (method, url, data) {
|
20 | 30 | return new Promise((resolve, reject) => {
|
21 | 31 | const xhr = new window.XMLHttpRequest()
|
|
34 | 44 | })
|
35 | 45 | }
|
36 | 46 |
|
37 |
| - function uploadFiles (e, fileInput, name) { |
| 47 | + function uploadFiles (form, fileInput, name) { |
38 | 48 | const url = fileInput.getAttribute('data-url')
|
39 |
| - const form = e.target |
40 | 49 | const promises = Array.from(fileInput.files).map((file) => {
|
41 | 50 | const s3Form = new window.FormData()
|
42 | 51 | Array.from(fileInput.attributes).forEach(attr => {
|
|
60 | 69 | input.type = 'hidden'
|
61 | 70 | input.name = 's3file'
|
62 | 71 | input.value = fileInput.name
|
63 |
| - form.appendChild(input) |
64 | 72 | fileInput.name = ''
|
65 |
| - form.submit() |
| 73 | + form.appendChild(input) |
| 74 | + window.uploading -= 1 |
66 | 75 | }, (err) => {
|
67 | 76 | console.log(err)
|
68 | 77 | fileInput.setCustomValidity(err)
|
69 | 78 | fileInput.reportValidity()
|
70 | 79 | })
|
71 |
| - } |
72 | 80 |
|
73 |
| - function addHandlers (fileInput) { |
74 |
| - const form = fileInput.closest('form') |
75 |
| - form.addEventListener('submit', (e) => { |
76 |
| - uploadFiles(e, fileInput, fileInput.name) |
77 |
| - e.preventDefault() |
78 |
| - }, false) |
79 | 81 | }
|
80 | 82 |
|
81 | 83 | document.addEventListener('DOMContentLoaded', () => {
|
82 |
| - [].forEach.call(document.querySelectorAll('.s3file'), addHandlers) |
| 84 | + let forms = Array.from(document.querySelectorAll('.s3file')).map(input => { |
| 85 | + return input.closest('form') |
| 86 | + }) |
| 87 | + forms = new Set(forms) |
| 88 | + forms.forEach(form => { |
| 89 | + form.onsubmit = (e) => { |
| 90 | + e.preventDefault() |
| 91 | + window.uploading = 0 |
| 92 | + const inputs = document.querySelectorAll('.s3file') |
| 93 | + Array.from(inputs).forEach(input => { |
| 94 | + window.uploading += 1 |
| 95 | + uploadFiles(form, input, input.name) |
| 96 | + } |
| 97 | + ) |
| 98 | + waitForAllFiles(form) |
| 99 | + } |
| 100 | + }) |
83 | 101 | })
|
84 | 102 |
|
85 |
| - document.addEventListener('DOMNodeInserted', (e) => { |
86 |
| - if (e.target.tagName) { |
87 |
| - const el = e.target.querySelector('.s3file') |
88 |
| - if (el) addHandlers(el) |
89 |
| - } |
90 |
| - }) |
91 | 103 | })()
|
0 commit comments