代码之家  ›  专栏  ›  技术社区  ›  Vickie Jack

无法在Spring MVC 4+Ajax中使用其他表单字段上载图像

  •  0
  • Vickie Jack  · 技术社区  · 6 年前

    我想创建一个在Web应用程序中添加用户的表单,在Java + Spring MVC 4 + Hibernate 4 + jQuery AJAX中使用Tomcat 9编写。

    这是我的表格:

            <form:form id="id1" name="addUser" class="form-horizontal form-material" data-toggle="validator"
                       method="post"
                       action="javascript:void(0)" enctype="multipart/form-data">
                <div class="form-group">
                    <div class="col-md-12 m-b-20">
                        <input name="name" type="text" placeholder="${msg_name}" class="form-control"
                               data-required-error="${msg_requiredInput}"
                               required>
                    </div>
                    <div class="col-md-12 m-b-20">
                        <input name="mobile" type="text" class="form-control" placeholder="${msg_mobile}">
                    </div>
                    <div class="col-md-12 m-b-20">
                        <input name="phone" type="text" class="form-control" placeholder="${msg_phone}">
                    </div>
                    <div class="col-md-12 m-b-20">
                        <input name="email" type="email" class="form-control" placeholder="${msg_email}">
                    </div>
                    <div class="col-md-12 m-b-20">
                        <div class="fileupload btn btn-danger btn-rounded waves-effect waves-light">
                            <span><i class="ion-upload m-l-5"></i>
                                ${msg_sendPicture}
                            </span>
                            <input name="file" id="file" type="file" class="upload">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="addUerSubmit" type="submit" class="btn btn-info waves-effect">
                            ${msg_save}
                    </button>
                    <button type="button" class="btn btn-default waves-effect"
                            data-dismiss="modal">
                            ${msg_cancel}
                    </button>
                </div>
            </form:form>
    

    我的Ajax请求是:

    <script type="text/javascript">
        $(function () {
            $('#addUserSubmit').click(function (e) {
                if ($(this).hasClass('disabled'))
                    return;
                $.ajax({
                    url: 'addUser',
                    method: 'POST',
                    dataType: 'json',
                    async: false,
                    cache: false,
                    processData: false,
                    data: $('form[name=addUser]').serialize(),
                    success: function (res) {
                        showAlert(res.type, res.message);
                    }
                })
            });
        });
    </script>
    

    以下代码是我的控制器:

    @ResponseBody
        @PostMapping("/addUser")
        public void addUser(@RequestParam("name") String name,
                                         @RequestParam("mobile") String mobile,
                                         @RequestParam("phone") String phone,
                                         @RequestParam("email") String email,
                                         @RequestParam("file") MultipartFile file) {
            ServletContext servletContext = request.getServletContext();
            User user = new User(name, mobile, phone, email);
            userService.addUser(user);
    
            try {
                if (file != null)
                    FileCopyUtils.copy(file.getBytes()
                            , new File(servletContext.getRealPath("/files/users/") + user.getId()));
                else
                    FileCopyUtils.copy(new File(servletContext.getRealPath("/files/users/user.png"))
                            , new File(servletContext.getRealPath("/files/users/") + user.getId()));
            } catch (IOException e) {
          e.printStack();
    
            }
    
        }
    

    但当我运行这个程序时,服务器返回错误500,服务器显示以下错误:

    22-Jul-2018 18:12:36.506 SEVERE [http-nio-8080-exec-8] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [spring-mvc] in context with path [/spring] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause
     org.springframework.web.multipart.MultipartException: Current request is not a multipart request
        at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:190)
        at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:109)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    
    .........
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   rieckpil    6 年前

    我认为如果您使用自定义的javascript函数而不是HTML的默认行为 form 您必须配置Ajax调用,以便它将数据发送为 multipart/form-data 即使您在 <form> 元素Ajax调用将不使用此配置。请看下面关于stackoverflow的关于如何将数据包装为 FromData 对于Ajax调用: Sending multipart/formdata with jQuery.ajax