JavaScript – How to Add Files to HTML File Input Field Without Replacing

htmljavascript

I'm trying to create a Html file input field which can add multiple files to the form, instead of replacing existing chosen files.

This is the basic file input element for uploading multiple files:

<input type="file" id="fileupload" multiple>

But it replaces previously chosen files 🙁

I can't believe that html doesn't have a built-in functionality for adding multiple files, but all solutions i have seen so far involve adding some external library which is not ideal.

Best Answer

I think this is question for SO.

The file field, multiple or not, will always replace the previous selection. What you have to do is store the selection somewhere else each time user selects a file.

The file field has a property files, which contains a FileList object, which is basically a list of File objects, each one with some properties like name, type and size.

If you listen to the change event, you could just add the files just selected to your own variable and even present them to the user and allow him to remove a file. You could immediately start uploading the files via AJAX or submit all files when the form is submitted.

See:

https://www.w3.org/TR/FileAPI/#dfn-filelist

https://stackoverflow.com/questions/16742956/file-field-append-file-list

Related Topic