I’m following this tutorial to try to figure out how to build a drag-and-drop file upload box. I can’t use jQuery. The problem is that when I release a file over the box, the form automatically submits to the target specified in the form action
property despite my trying to override it. Any ideas? I have copied out the upload box –
<form id="uploader" class="box" method="post" action="" enctype="multipart/form-data">
<div class="box__input">
<svg class="box__icon" xmlns="http://www.w3.org/2000/svg" width="50" height="43" viewBox="0 0 50 43"><path d="M48.4 26.5c-.9 0-1.7.7-1.7 1.7v11.6h-43.3v-11.6c0-.9-.7-1.7-1.7-1.7s-1.7.7-1.7 1.7v13.2c0 .9.7 1.7 1.7 1.7h46.7c.9 0 1.7-.7 1.7-1.7v-13.2c0-1-.7-1.7-1.7-1.7zm-24.5 6.1c.3.3.8.5 1.2.5.4 0 .9-.2 1.2-.5l10-11.6c.7-.7.7-1.7 0-2.4s-1.7-.7-2.4 0l-7.1 8.3v-25.3c0-.9-.7-1.7-1.7-1.7s-1.7.7-1.7 1.7v25.3l-7.1-8.3c-.7-.7-1.7-.7-2.4 0s-.7 1.7 0 2.4l10 11.6z"></path></svg>
<br>
<input class="box__file" type="file" name="files[]" id="file" data-multiple-caption="{count} file selected" multiple />
<label class="file-label" for="file"><strong>Choose a file</strong><span class="box__dragndrop"> or drag it here</span>.</label>
</div>
<div class="box__uploading">Uploading…</div>
<div class="box__success">Done!</div>
<div class="box__error">Error! <span></span>.</div>
<button class="box__button" type="button">Upload</button>
</form>
and I have the following in javascript below it:
var isAdvancedUpload = function() {
var div = document.createElement('div');
return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 'FormData' in window && 'FileReader' in window;
}();
var form = document.querySelector('.box');
if (isAdvancedUpload) {
form.className += " " + 'has-advanced-upload';
}
if (isAdvancedUpload) {
var droppedFiles = false;
'drag dragstart dragend dragover dragenter dragleave drop'.split(" ").forEach(function(e) {
window.addEventListener(e, function(f){
f.preventDefault();
f.stopPropagation();
}, false);
});
window.addEventListener('dragover',
()=>form.classList.add('is-dragover'),
false
);
window.addEventListener('dragenter',
()=>form.classList.add('is-dragover'),
false
);
window.addEventListener('dragleave',
()=>form.classList.remove('is-dragover'),
false
);
window.addEventListener('dragend',
()=>form.classList.remove('is-dragover'),
false
);
window.addEventListener('dragdrop',
()=>form.classList.remove('is-dragover'),
false
);
window.addEventListener('drop',
(e)=>{
droppedFiles = e.dataTransfer.files;
console.log(droppedFiles);
form.submit();
},
false
);
form.addEventListener('submit', function(e) {
form = document.querySelector("#uploader");
if ('is-uploading' in form.classList) return false;
form.classList.add('is-uploading');
form.classList.remove('is-error');
input = document.querySelector('input[type="file"]');
/* code here to collect the input, package it as a FormData, and fetch it to a specific POST endpoint */