I am trying filter some of the user selected files in a multiple file input element in my html5 form prior to submission. It seems like you can either remove ALL of the user selected files from any file input on the form or none of the user selected files from a file input before submitting the form and uploading to server. It would be nice to be able to remove just any offending files before uploading. Otherwise must allow the files to be uploaded and have php deal with the uploaded files post submission. Thanks for any ideas.
CodePudding user response:
It looks like my suspicions were confirmed and the only way to add files to a file input is to set it equal to a dataTransfer object, ie:
fileInput.files=evt.dataTransfer.files;
evt.dataTransfer.files represents the files the user selected/dropped and cannot be changed via js code on the page.
I was not able to add files to a file input using formData.append() to append single files over multiple additive iterations to a file input.
This solution below is working. The process is to instantiate your own dataTransfer object on page load. Then get the user uploaded files from evt.dataTransfer.files on each drag or browse and iterate through them. When you find files that meet your criteria add them to your own custom dataTransfer object. Once your own dataTransfer object is all set with the files you want added after each user drop, update fileInput.files= your own dataTransfer object.
onload:
var dT=new dataTransfer(); var fileInput=document.forms[0].elements['files[]'];
//now on each drop you will get the user selected files as:
evt.dataTransfer.files
so you always start with that.
function dropHandler(evt) {
//prevent default action
evt.preventDefault();
evt.stopPropagation();
//for each file in the user selection, validate them as you wish
//and only add the ones you want to the dataTransfer object you already created.
for (const file of evt.dataTransfer.files) {
//if this validate that etc
//if file is good to add
dT.items.add(file);
}
//at the end of each drop
//once you have added only the files you want to your own dT object
//update your form's file input's files to the latest version of your dT object's files
fileInput.files=dT.files;
}//end drop handler function`
Now you have your form's file input populated with only the user selected files you want, have weeded out the rest and are ready for form submission.