Spring Ajax 文件上传

Spring Ajax file upload

我正在使用 jquery ajaxSubmit 函数来提交我的表单。我在表单中也有文件上传字段。

这是 ajaxSubmit 函数的代码。

$('#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;
        });

这是我的控制器方法

@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";

}

现在的问题是,如果我 select 用于上传和提交表单的文件一切正常。但是如果我在没有 selecting 文件的情况下提交表单,它会在浏览器控制台中给出 400 Bad request 错误。找不到问题所在。

有线索吗?

已解决。问题是因为 ajax。如果我没有 select 文件,它会发送空字符串来代替文件。

现在的解决方案是,我在提交表单之前检查文件是否已 selected。如果没有,我用 jquery

禁用该字段
if($("#policyBriefFiles").val()==""){
        $("#policyBriefFiles").prop('disabled', true);
}

生活很美好:)