I'm trying to build a file upload form with the following conditions.
Selected files are always added to file list to be uploaded, instead of overwriting it which is the default behaviour of <input type="file" multiple />
you can remove the files that are already chosen
when you submit the form, it refreshes the entire page as traditional plain submit tag does (as opposed to updating specific html content with ajax)
1 and 2 can easily be done by javascript plugins, for instance dropzonejs and jquery-fileupload. here's a good example that does 1 and 2 with jquery-fileupload. (http://jsfiddle.net/eLLWN/24/)
But all of these js plugins don't use file input's value field. They're designed to store selected files in javascript array to send by ajax.
After googling around, I wanna ask 2 things.
It's not possible to remove selected files or choose additional files on plain file input field, because javascript's "FileList" object is readonly. correct?
Supposing above is correct, my workaround is giving up condition 3. and replacing the entire page content with the response of ajax. Any of you come up with better alternatives?
If you do not need something very complicated, you could just dynamically add file inputs when a file has been selected, and add a remove button next to the selected file. It only takes a few lines using jQuery, for example:
<form method="POST" action="/file-upload" enctype="multipart/form-data">
<div id="uploads">
</div>
<input type="submit" value="Upload!">
</form>
<script id="upload-template" type="text/template">
<div class="upload">
<input class="upload-input" type="file" name="file[]">
<div class="file hidden">
<span class="filename"></span>
<button class="delete" type="button">Delete</button>
</div>
</div>
</script>
<style>
.hidden {
display: none;
}
</style>
<script>
$(function() {
var addUploader = function() {
var template = $('#upload-template').html();
$('#uploads').append(template);
};
$('#uploads').on('change', '.upload-input', function() {
var fileName = $(this).val().replace(/^.*[\\\/]/, '');
$(this).addClass('hidden');
$(this).siblings('.file').removeClass('hidden');
$(this).siblings('.file').children('.filename').text(fileName);
addUploader();
});
$('#uploads').on('click', '.delete', function() {
$(this).parents('.upload').remove();
});
addUploader();
});
</script>
Here is a working example: http://jsfiddle.net/d851oxmn/1/