0
votes

I am developing an employee registration form in spring. I have used two ajax call, one is for employee information and other one is for upload e file(image)and store them in a specific folder in single jsp page and single controller.Here is my jsp page:

 function onuploadCall(){

    var file = $('[name="file"]');
    console.log(file);
   var filename = $.trim(file.val());
   console.log(filename);
     //var imgContainer = $('#imgContainer');

    var formData = new FormData();
    formData.append('file', jQuery('input[type=file]')[0].files[0]);

    $.ajax({
        url: "http://localhost:8080/EmployeeRegistrationForm/echofile",
        type: "POST",
        async:true,
        data: formData,
        enctype: "multipart/form-data",
        processData: false,
        modelAttribute:'uploadedFile',
        contentType: true,

       success: function(response){

            var obj = JSON.parse(response);
            alert(response);

        },

        error: function(){                      
            alert('Error while request..');
        }
    });
     /*  }).done(function(data) {
         // imgContainer.html('');
          var img = '<img src="data:' + data.contenttype + ';base64,'
              + data.base64 + '"/>';
         alert("success");
         // imgContainer.append(img);
      }).fail(function(jqXHR, textStatus) {
          //alert(jqXHR.responseText);
          alert('File upload failed ...');
      });    */
}
function madeAjaxCall(){


    array();
     var gender = $('#gender').val();
     var blood = $('#blood').val();


    $.ajax({
        type: "post",
        url: "http://localhost:8080/EmployeeRegistrationForm/employee",
        cache: false,       
        async:false,


       data:'name=' + $("#name").val() 
           +"&fname=" + $("#fname").val() 
           +"&mname=" + $("#mname").val() 
           +"&nid=" + $("#nid").val() 
           +"&age=" + $("#age").val()
           +"&blood=" + blood
           +"&gender=" + gender 
           +"&caddress=" + $("#caddress").val() 
           +"&paddress=" + $("#paddress").val()
           +"&paddress=" + $("#paddress").val()
           +"&pdegree=" + $("#pdegree").val()
           +"&puniversity=" + $("#puniversity").val()
           +"&pyear="+ $("#pyear").val()
           +"&presult=" + $("#presult").val()
           +"&mdegree=" + $("#mdegree").val()
           +"&muniversity=" + $("#muniversity").val()
           +"&mresult=" + $("#mresult").val()
           +"&myear=" + $("#myear").val()
           +"&bdegree=" + $("#bdegree").val()
           +"&buniversity=" + $("#buniversity").val()
           +"&bresult=" + $("#bresult").val()
           +"&byear=" + $("#byear").val()
           +"&hdegree=" + $("#hdegree").val()
           +"&college=" + $("#college").val()
           +"&hresult=" + $("#hresult").val()
           +"&hyear=" + $("#hyear").val()
           +"&sdegree=" + $("#sdegree").val()
           +"&school=" + $("#school").val()
           +"&sresult=" + $("#sresult").val()
           +"&syear=" + $("#syear").val()
           +"&date=" + $("#date").val()
           +"&department=" + $("#department").val()
           +"&location=" + $("#location").val()
           +"&company=" + company
           +"&from=" + from
           +"&to=" + to
           +"&year=" + year
           +"&organization=" + organization
           +"&topic=" + topic
           +"&duration=" + duration,

        success: function(response){

            var obj = JSON.parse(response);
            alert(response);

        },

        error: function(){                      
            alert('Error while request..');
        }
    });
}

Here is my controller:

@Controller
public class imageUploadController {

     @RequestMapping(value = "/echofile",method = RequestMethod.POST)
        public @ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
                HttpServletResponse response ,  @ModelAttribute("uploadedFile") UploadedFile upldfile) throws Exception {

            InputStream inputStream = null;
            OutputStream outputStream = null;
           MultipartFile multipartFile = request.getFile("file");

            MultipartFile file = upldfile.getFile();
            String fileName = multipartFile.getOriginalFilename();
            System.out.println("vcvvvvvvvv"+fileName);
            upldfile.setFile(file);

            Long size = file.getSize();
            String contentType = multipartFile.getContentType();

            InputStream stream = multipartFile.getInputStream();
            byte[] bytes = IOUtils.toByteArray(stream);

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("fileoriginalsize", size);
            map.put("contenttype", contentType);
            map.put("base64", new String(Base64Utils.encode(bytes)));

            try {


                inputStream = file.getInputStream();

                   File newFile = new File("E:/Java_Project/EmployeeRegistrationForm/src/main/webapp/resources/image/"+ fileName);
                   if (!newFile.exists()) {
                    newFile.createNewFile();
                   }
                   outputStream = new FileOutputStream(newFile);
                   int read = 0;
                  // byte[] bytes = new byte[1024];

                   while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                   }
                  } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                  }

            return map;
        }


}

But this shows the error:

EVERE: Servlet.service() for servlet [dispatcher] in context with path [/EmployeeRegistrationForm] threw exception [Request processing failed; nested exception is org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public java.util.HashMap EmployeeRegistrationForm.controller.imageUploadController.echoFile(org.springframework.web.multipart.MultipartHttpServletRequest,javax.servlet.http.HttpServletResponse,EmployeeRegistrationForm.model.UploadedFile) throws java.lang.Exception]; nested exception is java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]: org.apache.catalina.connector.RequestFacade@618dfe29] with root cause java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]: org.apache.catalina.connector.RequestFacade@618dfe29

Here is my dispatch-servlet:

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <context:component-scan base-package="EmployeeRegistrationForm.controller" />
<mvc:resources mapping="/resources/**" location="/resources/" />
 <mvc:annotation-driven />
 <mvc:default-servlet-handler />
  <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576"/>
    </bean>


</beans>

Why it shows this error???When I input text data, it has been called an ajax call in controller /employee, it works.but when I am trying to upload a file and call ajax by clicking upload button in same jsp page and in same controller /echofile-it shows this error. Where is the problem?

Here is full jsp page

1
Did you read the exception carefully? nested exception is java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]: - Jim Garrison

1 Answers

0
votes

I have changed few things on my project. On jquery:

function uploadImage() {

            var file = $('[name="file"]');
            //var imgContainer = $('#imgContainer');

            var formData = new FormData();
            formData.append('file', jQuery('input[type=file]')[0].files[0]);
            var filename = $.trim(file.val());

            if (!(isJpg(filename) || isPng(filename))) {
                alert('Please browse a JPG/PNG file to upload ...');
                return;
            }

             $.ajax({
                url: "http://localhost:8080/EmployeeRegistrationForm/echofile",
                type: "POST",
                data: new FormData(document.getElementById("fileForm")), 
                //data: formData,
                enctype: 'multipart/form-data',
                processData: false,
                aync: false,
                modelAttribute:'uploadedFile',
                headers: {'Content-Type': 'multipart/form-data'},
                contentType: false,
             /*  }).done(function(data) {

                 var img = '<img src="data:' + data.contenttype + ';base64,'
                      + data.base64 + '"/>';
                  alert("success");

             }).fail(function(jqXHR, textStatus) {

                  alert('File upload failed ...');
              });  */

            success: function(response){

                var obj = JSON.parse(response);
                alert(response);

            },

            error: function(){                      
                alert('Error while request..');
            }
        });   
        }

and my controller is:

@RequestMapping(value = "/echofile",method = RequestMethod.POST)
        public @ResponseBody HashMap<String, Object> echoFile(HttpServletRequest  request,
                HttpServletResponse response ,  @ModelAttribute("uploadedFile") UploadedFile upldfile) throws Exception {
         HashMap<String, Object> map = new HashMap<String, Object>();

         if(request instanceof MultipartHttpServletRequest){

             InputStream inputStream = null;
                OutputStream outputStream = null;
              // MultipartFile multipartFile = request.getFile("file");

                MultipartFile file = upldfile.getFile();
                String fileName = file.getOriginalFilename();
                System.out.println("vcvvvvvvvv"+fileName);
                upldfile.setFile(file);

                Long size = file.getSize();
                String contentType = file.getContentType();

                InputStream stream = file.getInputStream();
                byte[] bytes = IOUtils.toByteArray(stream);


                map.put("fileoriginalsize", size);
                map.put("contenttype", contentType);
                map.put("base64", new String(Base64Utils.encode(bytes)));

                try {


                    inputStream = file.getInputStream();

                       File newFile = new File("E:/Java_Project/EmployeeRegistrationForm/src/main/webapp/resources/image/"+ fileName);
                       if (!newFile.exists()) {
                        newFile.createNewFile();
                       }
                       outputStream = new FileOutputStream(newFile);
                       int read = 0;
                      byte[] byt = new byte[1024];

                       while ((read = inputStream.read(byt)) != -1) {
                        outputStream.write(byt, 0, read);
                       }
                      } catch (IOException e) {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
                      }


         }
         return map; 


         }

This is my full jsp page