为什么我无法在春天将上传的文件保存在rsesources / images文件夹中?

时间:2016-12-22 06:10:16

标签: ajax spring-mvc servlets

这是一个使用ajax调用的spring项目。我想将上传的图像保存在resources / images文件夹中。 这是我的控制器:

@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;
        }

文件已上传并显示在index.jsp中。但它不存储在资源/图像文件夹中。

这是我的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>

模型是:

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


}

显示错误:

  

SEVERE:servlet [dispatcher]的Servlet.service()与上下文有关   path [/ SimpleAjaxJqueryPicUpload]抛出异常[请求处理   失败;嵌套异常是java.lang.ClassCastException:   SimpleAjaxJqueryPicUpload.model.UploadedFile无法强制转换为   具有根本原因的org.springframework.web.multipart.MultipartFile]   java.lang.ClassCastException:   SimpleAjaxJqueryPicUpload.model.UploadedFile无法强制转换为   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(未知来源)at   sun.reflect.DelegatingMethodAccessorImpl.invoke(未知来源)at   java.lang.reflect.Method.invoke(未知来源)at   org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)     在   org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)     在   org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)     在   org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)     在   org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)     在   org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)     在   org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)     在   org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:648)at   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:729)at   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)     在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)     在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)     在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)     在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)     在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)     在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)     在   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)     在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)     在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)     在   org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)     在   org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)     在   org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:745)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1437)     在   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)     在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)     在java.lang.Thread.run(未知来源)

我的dispatcher-servlet.xml是:

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

问题出在哪里?

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。我必须改变一些事情。 我必须改变ajax电话。

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

我必须添加 modelAttribute:'uploadedFile'

  1. 然后我更换了控制器。我的控制器是:

    @Controller // @ RequestMapping( “/连续”) 公共类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;
        }
    
  2. 然后问题就解决了!!!!!!!!!!!! :d