0
votes

This is a spring project using ajax call.I want to save the uploaded image in the resources/images folder. Here is my controller:

@Controller
//@RequestMapping("/cont")
public class RestController {

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

              InputStream inputStream = null;
              OutputStream outputStream = null;

            UploadedFile upldfile = new UploadedFile();
            MultipartFile multipartFile = request.getFile("file");

            upldfile.setFile(multipartFile);
            String fileName = multipartFile.getOriginalFilename();



            Long size = multipartFile.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 = ((MultipartFile) upldfile).getInputStream();

                   File newFile = new File("E:/Java Project/SimpleAjaxJqueryPicUpload/src/main/resources/images" + 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;
        }

The file is uploaded and show in the index.jsp. But it is not stored in resources/images folder.

Here is my index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC - Upload File</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://malsup.github.com/jquery.form.js"></script>

<script type="text/javascript">

var isJpg = function(name) {
    return name.match(/jpg$/i)
};

var isPng = function(name) {
    return name.match(/png$/i)
};

$(document).ready(function() {
    var file = $('[name="file"]');
    var imgContainer = $('#imgContainer');

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

    $('#btnUpload').on('click', function() {
        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/SimpleAjaxJqueryPicUpload/api/echofile",
            type: "POST",
           /*  data: new FormData(document.getElementById("fileForm")), */
            data: formData,
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false
          }).done(function(data) {
              imgContainer.html('');
              var img = '<img src="data:' + data.contenttype + ';base64,'
                  + data.base64 + '"/>';

              imgContainer.append(img);
          }).fail(function(jqXHR, textStatus) {
              //alert(jqXHR.responseText);
              alert('File upload failed ...');
          });

    });

    $('#btnClear').on('click', function() {
        imgContainer.html('');
        file.val('');
    });
});

</script>
</head>

<body>
<body style="font-family: calibri; font-size: 8pt">
<div>
<div id="fileForm">
    <input type="file" name="file" id="image"/>
    <button id="btnUpload" type="button">Upload file</button>
    <button id="btnClear" type="button">Clear</button>
</div>
<div id="imgContainer"></div>
</div>
</body>
</html>

And the model is:

package SimpleAjaxJqueryPicUpload.model;

import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class UploadedFile {

      public int length;
        public byte[] bytes;
        public String name;
        public String type;
        private MultipartFile file;

        public MultipartFile getFile() {
         return file;
        }

        public void setFile(MultipartFile file) {
         this.file = file;
        }


}

It shows an error:

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/SimpleAjaxJqueryPicUpload] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: SimpleAjaxJqueryPicUpload.model.UploadedFile cannot be cast to org.springframework.web.multipart.MultipartFile] with root cause java.lang.ClassCastException: SimpleAjaxJqueryPicUpload.model.UploadedFile cannot be cast to org.springframework.web.multipart.MultipartFile at SimpleAjaxJqueryPicUpload.controller.RestController.echoFile(RestController.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:745) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)

my dispatcher-servlet.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

     <context:component-scan base-package="SimpleAjaxJqueryPicUpload.controller" />
     <mvc:annotation-driven />

     <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576"/>
    </bean>
</beans>

Where is the problem?

1

1 Answers

0
votes

I have solved the question.I have to change few things. 1. I have to change in ajax call.

 url: "http://localhost:8080/SimpleAjaxJqueryPicUpload/api/echofile",
            type: "POST",
            data: formData,
            enctype: 'multipart/form-data',
            processData: false,
            modelAttribute:'uploadedFile',
            contentType: false

I have to added modelAttribute:'uploadedFile'

  1. Then I have changed my controller. My controller is:

    @Controller //@RequestMapping("/cont") public class RestController {

      @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 = file.getOriginalFilename();
    
            upldfile.setFile(file);
            String fileName2 = multipartFile.getOriginalFilename();
    
    
    
            Long size = multipartFile.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 = ((MultipartFile) upldfile).getInputStream();
    
                inputStream = file.getInputStream();
    
                   File newFile = new File("E:/Java Project/SimpleAjaxJqueryPicUpload/src/main/resources/images/" + 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;
        }
    

Then the problem has been solved!!!!!!!!!!!! :D