3

I am new for Spring MVC and AJAX file upload. I tried to upload a file using ajax but i am getting 400 bad request error. I searched a lot of solutions for but i can't get a correct solution. Please help me.

Here my code,

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>

Thanks in advance...

1 Answer 1

1

Please change this lines

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

with this one

 var data = new FormData(this);

then it will work fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.