Programmatically remove 1 or more files from upload in html5?

By | July 12, 2018
Questions:

I have the below. In dostuff I’d like to remove 1 or more files (but not all) from my file uploads.

The only images I accept are png, jpg and gif. Bmp, svg and etc will get the form rejected.

I do a check in Javascript but I’d like to prompt asking if I can remove the unaccepted files (bmp, etc.) and continue. How might I remove the files from upload programmatically?

<input type='file' name='uploads[]' multiple="" 
       onchange="dostuff(this);" accept="image/*"  />
Answers:

I’ve run into this issue recently as well. I’m using jQuery to solve my problem, which means it could be translated into vanilla js if you wanted to do that. Here’s a code snippet:

function clearFileInput(){
   var fileInput = $('#your-file-input-selector');
   var fileInputContainer = fileInput.parent();
   var fileInputClone = fileInput.clone();

   fileInput.remove();
   fileInputContainer.append(fileInputClone);  
}

Hope this helps!

Questions:
Answers:

You can access the files as an array, then just manipulate the array as needed to remove unaccepted files.

<script type="text/javascript">
    function dostuff(input) {
        var output = 'All Files:<br />';
        var validOutput = '<br />Valid Files:<br />';
        var validFiles = [];
        for(var i = 0; i < input.files.length; i++) {
            if(input.files[i].name.substr(-3, 3) != 'jpg') {
                alert(input.files[i].name + ' is invalid');
            }
            else {
                validFiles.push(input.files[i]);
                validOutput += input.files[i].name;
            }
            output += input.files[i].name + '<br />';
        }
        output += validOutput;
        document.getElementById('output').innerHTML = output;
    }
</script>

<input type='file' name='uploads[]' multiple="" onchange="dostuff(this);" accept="image/*"  />
<div id="output"></div>

Fiddle here.

Leave a Reply

Your email address will not be published. Required fields are marked *