I'll try to make this question as simple as I can. I want to upload a file with additional form data via an AJAX submission using JQuery (but also for it to be compatible with ie 7 or ie 8, and asynchronous too)
Without the submit being an AJAX submission via JQuery, the process works fine. Namely I did the following:
- declared CommonsMultipartResolver
- In controller wrote this handler method
@RequestMapping(value="/processfileupload", method = RequestMethod.POST) public @ResponseBody String handleFileUpload(UploadForm data, BindingResult result) throws Exception {
....
}
Where UploadForm is a Spring MVC form object which I bound to the form. Also, I bound the formObject in Spring's form tag like so: enctype="multipart/form-data" .. etc..
Like I said, works perfectly if it is NOT done via an Ajax call via JQuery. Once I tried to make it an Ajax call, the file is always null.
Here is the Ajax call via JQuery
function submitFileUploadViaAjax() {
$.ajax({
url: "processfileupload",
data: $("#file_upload_form").serialize(),
type: "POST",
processData: false,
contentType: false,
success: function(data) {
$(response).html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.readyState == 0 || xhr.status == 0) {
// not really an error
return;
} else {
alert("XHR Status = "+xhr.status);
alert("Thrown Error = "+thrownError);
alert("AjaxOptions = "+ajaxOptions)
}
}
});
}
I suspect the problem may be: data: $("#file_upload_form").serialize(),
I have read some suggested solutions for those with similar problems to use a formData object but have read that this won't be compatible with IE 7 or IE 8, is this true?
I head also read the JQuery file upload plug-in would work ( https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-form-data) but I'm not sure if I'd be able to wire this into spring with spring's great way of binding form data to a form object and then just injecting it into a controller.
Does anyone have their thoughts on the best way to upload a file (relatively small) + have some form data, and be able to process this with a single endpoint in a spring mvc controller? And the solution so that it is compatible with most browsers, but especially will work with ie 7 or ie 8 (it's a requirement it work in those browsers.)
Thanks a bunch!
- Rocco