0

i want to create form for adding user with image in web application that written in java + spring mvc 4 + hibernate 4 + jquery ajax with tomcat 9.

it is my form:

        <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>

and my ajax request is:

<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>

and following code is my controller:

@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();

        }

    }

but when i run this program sever return error with 500 and server show following error :

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)

.........
Vickie Jack
  • 95
  • 1
  • 10

1 Answers1

2

I think if you use a custom JavaScript function and not the default behaviour of the HTML form you have to configure your AJAX call so that it will send the data as multipart/form-data even if you configured this at your <form> element your AJAX call won't use this configuration. Have look at the following answer on Stackoverflow on how to wrap your data as FromData for the AJAX call: Sending multipart/formdata with jQuery.ajax

rieckpil
  • 10,470
  • 3
  • 32
  • 56