I'm using BlueImp Jquery File Upload to add file uploading capabilities to an existing form. The plug-in works great when files are selected i.e. when you always upload some files with the form, but in my case I want the file upload part to be optional so the user can submit the form with just text inputs populated.
The question of how to allow File Upload to do this has been asked several times both on Stack Overflow (ref 1, ref 2) and on the GitHub project itself (ref) with no suitable answers so I'm now trying to tackle this a slightly different way.
The only way I can think of to this is to create a stand-alone submit button which first handles the 'normal' (non file upload) form fields via an AJAX call, then on success it programmatically triggers the upload of the files in a separate process. Far from ideal but the only way I can conceive getting the process to work.
I have the text part of the form post and the file upload part of the post working now, but it's only uploading the first file if I select multiple files in the input, presumably this is because the function which creates the array of files on the input change event is only able to detect one file per input - even though there may be many.
Here's the code:
$(function () {
'use strict';
var myFiles = new Array();
$('.files').bind('change', function (e) {
var f;
f = e.target.files || [{ name: this.value }];
myFiles.push(f[0]);
});
// Initialize the jQuery File Upload widget:
$('#fileupload1').fileupload({
url: '/something/api/UploadApi/PostFiles',
singleFileUploads: false
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload1').fileupload(
'option',
'redirect',
window.location.href.replace(/\/[^\/]*$/, '/cors/result.html?%s')
);
// Start things off when submit button clicked
$('#messageSubmit1').click(function () {
var message = $('textarea', form).val();
if (!message) {
alert('Please enter a message!');
return false;
}
// Post text data
$.ajax({
url: '/something/api/MessageApi/AddMessage/',
data: {
'message': message
},
dataType: 'xml',
success: function (responseXML) {
// When text data saved successfully, post files
$('#fileupload1').fileupload('send', { files: myFiles });
}
});
return false;
});
Can anyone see how to get this working, or suggest a better approach. It seems very hacky but I've drawn a complete blank in searching for a solution for this (seemingly fairly common) problem.
Many thanks!