400(错误请求)错误 - Spring MVC 文件上传使用 JQuery AJAX

400 (Bad Request) Error - Spring MVC File upload Using JQuery AJAX

我是 Spring MVC 和 AJAX 文件上传的新手。我尝试使用 ajax 上传文件,但出现 400 bad request 错误。我搜索了很多解决方案,但找不到正确的解决方案。请帮助我。

这是我的代码,

Users.java

public class Users {

    @NotNull
    private String firstName;
    @NotNull
    private String lastName;
    @NotNull
    private byte[] userPhoto;

   // getter and setter

}

UserController.java

public class UsersFormController {


    @RequestMapping(value = "/Appointment",method = RequestMethod.GET)
    public String appointmentView(Model model) {
        return "Appointment";
    }


        @RequestMapping(value="/FullRegistration", method=RequestMethod.POST)
    public @ResponseBody ValidationResponse fullRegistration(@Valid @ModelAttribute("user") Users user, BindingResult result, Model model, @RequestParam("photo") MultipartFile file){
        ValidationResponse res = new ValidationResponse();
    if(!result.hasErrors()){
         byte[] bytes = file.getBytes();
        user.setUserPhoto(bytes);
            res.setStatus("SUCCESS");
}
else{
res.setStatus("SUCCESS");
}
        return res;
    }
public class ValidationResponse {
    private String status;
// getter and setter
}

}

mvc-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">


    <annotation-driven />
    <context:component-scan base-package="com.aram.spring.emr" />

    <resources mapping="/resources/**" location="/resources/style/" />
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/pages/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- one of the properties available; the maximum file size in bytes -->
        <beans:property name="maxUploadSize" value="10000000" />
    </beans:bean>
</beans:beans>

Registration.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">

<title>Appointment Screen</title>

<script src="<c:url value="/resources/src/jquery-2.1.1.min.js" />"> </script>
                <spring:url value="/FullRegistration" var="full" />
</head>
<body>

<form id="Quick" enctype="multipart/form-data">
<input type="text" name="firstName">
<input type="text" name="lastName">
<input type="file" id="file1" name="photo">
<input type="submit" id="submit1">
</form>

<script type="text/javascript">

$(document).ready(function(){

                        $("#Quick").submit(function(e){
                            e.preventDefault();
                            var fields = $(this).find('input');
                            var data = new FormData();
                            for (var i = 0; i < fields.length; i++) {
                                var $item = $(fields[i]);
                                data.append($item.attr('name'), $item.val());
                            }
                            $.ajax({
                                    url: '${full}',
                                    processData: false,
                                    contentType: false,
                                    type: 'POST',
                                    data: data
                                }).done(function(response) {
                                    if (response.status == 'FAIL') {
                                        alert("request Failed")
                                    } else {
                                        alert("Patient Registration Successfully");
                                    }
                                }).fail(function(data){
                                    alert("<span class=\"formFieldError\">Server failed to process request</span>");
                                });

                            return false;
                        });
                });
        </script>

</body>
</html>

提前致谢...

请更改此行

  var fields = $(this).find('input');
                            var data = new FormData();
                            for (var i = 0; i < fields.length; i++) {
                                var $item = $(fields[i]);
                                data.append($item.attr('name'), $item.val());
                            }

用这个

 var data = new FormData(this);

那就可以正常工作了。