[英]How to validate files users are sending before uploading it to a server? - Javascript
Had minimal luck.运气极差。
In the below code snippet, I tried to first prevent event propagation so it wouldn't upload just yet.在下面的代码片段中,我试图首先阻止事件传播,这样它就不会上传。
I had the following assumptions.我有以下假设。
<html>
<input id="file-input" type="file">
</html>
...
<script>
let ignoreEventForSecondTime = false
document.getElementById("file-input").addEventListener("click", (event) => {
if (!ignoreEventForSecondTime) {
event.stopImmediatePropagation() // Don't actually upload yet
const input = event.target
validate(input.files) // I only want this to run after users have picked the files
ignoreEventTheSecondTime = true // Don't run this block after I refire the event
input.dispatchEvent(event) // The intention is to let whatever event listener handle uploading the files afterwards.
} else {
ignoreEventTheSecondTime = false
}
}, { capturing: true })
</script>
This seems to have worked.这似乎奏效了。 The problem was I couldn't just dispatch the same event I stopped propagation from, as well as changing from 'click' handler to 'change' handler so i can view files after the file dialog have completed.
问题是我不能只发送我停止传播的同一个事件,也不能从“点击”处理程序更改为“更改”处理程序,这样我就可以在文件对话框完成后查看文件。
<html>
<input id="file-input" type="file">
</html>
...
<script>
let ignoreEventForSecondTime = false
document.getElementById("file-input").addEventListener("change", (event) => { // LINE CHANGED
if (!ignoreEventForSecondTime) {
event.stopImmediatePropagation() // Don't actually upload yet
const input = event.target
validate(input.files)
ignoreEventTheSecondTime = true // Don't run this block after I refire the event
input.dispatchEvent(new Event('change', event)) // LINE CHANGED
} else {
ignoreEventTheSecondTime = false
}
}, { capturing: true })
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.