Skip to content

Commit bd9485d

Browse files
committed
Fix multi file support
1 parent 5967940 commit bd9485d

File tree

1 file changed

+30
-18
lines changed

1 file changed

+30
-18
lines changed

s3file/static/s3file/js/s3file.js

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,16 @@
1616
form.appendChild(input)
1717
}
1818

19+
function waitForAllFiles(form) {
20+
if (window.uploading !== 0) {
21+
setTimeout(() => {
22+
waitForAllFiles(form)
23+
}, 100)
24+
} else {
25+
form.submit()
26+
}
27+
}
28+
1929
function request (method, url, data) {
2030
return new Promise((resolve, reject) => {
2131
const xhr = new window.XMLHttpRequest()
@@ -34,9 +44,8 @@
3444
})
3545
}
3646

37-
function uploadFiles (e, fileInput, name) {
47+
function uploadFiles (form, fileInput, name) {
3848
const url = fileInput.getAttribute('data-url')
39-
const form = e.target
4049
const promises = Array.from(fileInput.files).map((file) => {
4150
const s3Form = new window.FormData()
4251
Array.from(fileInput.attributes).forEach(attr => {
@@ -60,32 +69,35 @@
6069
input.type = 'hidden'
6170
input.name = 's3file'
6271
input.value = fileInput.name
63-
form.appendChild(input)
6472
fileInput.name = ''
65-
form.submit()
73+
form.appendChild(input)
74+
window.uploading -= 1
6675
}, (err) => {
6776
console.log(err)
6877
fileInput.setCustomValidity(err)
6978
fileInput.reportValidity()
7079
})
71-
}
7280

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)
7981
}
8082

8183
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+
})
83101
})
84102

85-
document.addEventListener('DOMNodeInserted', (e) => {
86-
if (e.target.tagName) {
87-
const el = e.target.querySelector('.s3file')
88-
if (el) addHandlers(el)
89-
}
90-
})
91103
})()

0 commit comments

Comments
 (0)