I am using jquery ajaxSubmit function for submitting my form. I also have file upload field in the form.
Here's the code of ajaxSubmit function.
$('#wizard-p-7').submit(function(e) {
$(".validationMessage").hide();
e.preventDefault();
var formURL = $(this).attr("action");
$(this).ajaxSubmit({
url : formURL,
async : false,
contentType: 'multipart/form-data',
success : function(data) {
if (data == "version match.") {
check = true;
} else {
check = false;
}
},
error : function(jqXHR,
textStatus,
errorThrown) {
alert("error:"+errorThrown);
window.location = "<%=application.getContextPath()%>/pages/error/globalError.jsp";
}
});
e.preventDefault(); //STOP default action
// e.unbind(); //unbind. to stop multiple form submit.
return false;
});
Here is my controller method
@RequestMapping(value = "/sectioneight", method = RequestMethod.POST)
public @ResponseBody Object sectioneight(@ModelAttribute("iepDTO") ProjectDTO iepDTO,
@RequestParam("id") String id) {
try {
List<MultipartFile> files = iepDTO.getPolicyBriefFiles();
if(files!=null){
for(MultipartFile file : files){
String filePath = "C:/temp/" + file.getOriginalFilename();
File dest = new File(filePath);
file.transferTo(dest);
}
}
}
catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
logger.error("ProjectController - sectioneight : "+ e.getMessage());
}
return "redirect:home";
}
Now the problem is if I select a file for uploading and submit the form everything works fine. But if I submit the form without selecting file it gives 400 Bad request
error in the browser console. Can't find what is wrong.
Any clue?
Solved. Problem was because of ajax. If I don't select a file it sends null string in place of file.
The solution is now I check before submitting the form if file is selected or not. If not, I disable the field with jquery
if($("#policyBriefFiles").val()==""){
$("#policyBriefFiles").prop('disabled', true);
}
Life's good:)