I am creating and using a custom image uploader within my form which is submitted via ajax - everything works perfect.
I am allowing users to upload multiple images e.g:
<input type="file" name="files[]" accept="image/*" class="files-data" id="upload_images" multiple="">
The problem that I am facing, is that when a user clicks the "Image Upload Button" multiple times, each time the input (the array of previously uploaded images) is reset.
So if a user uploads 3 images, great - that works fine. But if they decide to open the file upload again and upload another image or two, the original 3 files are gone.
I am not looking for a plugin to do this, and I know that this can be done from other image uploaders I have seen.
Do you know how I can maintain previously uploaded images when the multiple input field is opened more than once?
Thank-you for any help.
This is the default behavior of HTML. You need to manage those uploaded files via javascript/jQuery in order to maintain the user selection and for which the plugins you are trying to escape from will do that for you :)
I solved this by looping through the uploaded images and storing them into an array each time a new file is uploaded. My problem was that I was doing something completely different, and just overriding the files each time the user uploads more files.
Some common sense, and sitting here to think for a while helped me solve this one :)
MyForm = {}; // empty array
MyForm.userUploads = []; // empty object
$('.add-listing-photos input[type="file"]').on('change', function() {
// Get the files.
var files = $(this)[0].files;
// For each file, append it onto the end of our array.
for( var key in files ) {
if( typeof( files[key] ) === 'object' ) {
MyForm.userUploads.push( files[key] );
}
}
console.log(MyForm.userUploads);
});
And then sent this through my ajax request.