有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法在spring mvc 4+ajax中与其他表单字段一起上载图像

我想创建一个表单,用java+spring mvc 4+hibernate 4+jquery ajax和tomcat 9编写的web应用程序添加带有图像的用户

这是我的表格:

        <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) 个答案

  1. # 1 楼答案

    我认为,如果您使用自定义JavaScript函数,而不是HTML form的默认行为,那么您必须配置AJAX调用,以便它将数据作为multipart/form-data发送,即使您在<form>元素中配置了此函数,您的AJAX调用也不会使用此配置。让我们看看下面关于Stackoverflow的答案,关于如何将AJAX调用的数据包装为FromDataSending multipart/formdata with jQuery.ajax