A simple example of an spring mvc of annotation uploading a file


spring mvc simple example of uploading a file.

There are a few caveats here

1. enctype= “multipart/ form-data” is required for uploading files

2. applicationContext. xml < bean id multipartResolver class ”= =” “org. springframework. web. multipart. commons. / CommonsMultipartResolver” > There is no shortage of configuration for file uploads

3, kiss these two jar bags can not be less oh, before because of the lack of the two jar, 1 directly reported 1 some weird mistakes, give me tired half dead ~ (version without any requirements)

commons-fileupload-1.2.2.jar

commons-io-2.0.1.jar

You can see the specific code as follows:

web.xml

<?xml version="0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://wwwworg/2001/XMLSchema-instance" xmlns="http://javasuncom/xml/ns/javaee" xmlns:web="http://javasuncom/xml/ns/javaee/web-app_2_xsd" xsi:schemaLocation="http://javasuncom/xml/ns/javaee http://javasuncom/xml/ns/javaee/web-app_2_xsd" id="WebApp_ID" version="5">
 <display-name>webtest</display-name>

 <listener>
    <listener-class>orgspringframeworkwebcontextContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      /WEB-INF/config/applicationContextxml
      /WEB-INF/config/codeifActionxml
    </param-value>
  </context-param>

  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>orgspringframeworkwebservletDispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/codeifActionxml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!--  Intercept all do Closing request  -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*do</url-pattern>
  </servlet-mapping>

 <welcome-file-list>
  <welcome-file>indexdo</welcome-file>
 </welcome-file-list>
</web-app>

applicationContext.xml

<?xml version="0" encoding="UTF-8"?>
<beans xmlns="http://wwwspringframeworkorg/schema/beans"
  xmlns:xsi="http://wwwworg/2001/XMLSchema-instance" xmlns:p="http://wwwspringframeworkorg/schema/p"
  xmlns:context="http://wwwspringframeworkorg/schema/context"
  xsi:schemaLocation="http://wwwspringframeworkorg/schema/beans http://wwwspringframeworkorg/schema/beans/spring-beans-xsd
  http://wwwspringframeworkorg/schema/context http://wwwspringframeworkorg/schema/context/spring-context-xsd"
  default-lazy-init="true">

  <!--  Start the Spring MVC Annotation function to complete requests and annotations POJO The mapping of  -->
  <bean class="orgspringframeworkwebservletmvcannotationAnnotationMethodHandlerAdapter" lazy-init="false" />

  <!--  You'd better join in DefaultAnnotationHandlerMapping Or you will be  XML Or other mapping coverage!  -->
  <bean class="orgspringframeworkwebservletmvcannotationDefaultAnnotationHandlerMapping" />

  <!--  Resolution of the model view name by adding a prefix and suffix to the model view name  -->
  <bean class="orgspringframeworkwebservletviewInternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix="jsp" />

  <!--  Support uploading files  -->
  <bean id="multipartResolver" class="orgspringframeworkwebmultipartcommonsCommonsMultipartResolver"/>

</beans>

codeifAction.xml

<?xml version="0" encoding="UTF-8"?>
<beans xmlns="http://wwwspringframeworkorg/schema/beans"
  xmlns:xsi="http://wwwworg/2001/XMLSchema-instance" xmlns:context="http://wwwspringframeworkorg/schema/context"
  xsi:schemaLocation="http://wwwspringframeworkorg/schema/beans http://wwwspringframeworkorg/schema/beans/spring-beans-xsd
  http://wwwspringframeworkorg/schema/context http://wwwspringframeworkorg/schema/context/spring-context-xsd"
  default-lazy-init="true">

  <bean id="uploadAction" class="comcodeifactionUploadAction" />

</beans>

UploadAction.java

package comcodeifaction;

import javaioFile;
import javautilDate;

import javaxservlethttpHttpServletRequest;

import orgspringframeworkstereotypeController;
import orgspringframeworkuiModelMap;
import orgspringframeworkwebbindannotationRequestMapping;
import orgspringframeworkwebbindannotationRequestParam;
import orgspringframeworkwebmultipartMultipartFile;

@Controller
public class UploadAction {

  @RequestMapping(value = "/uploaddo")
  public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {

    Systemoutprintln(" start ");
    String path = requestgetSession()getServletContext()getRealPath("upload");
    String fileName = filegetOriginalFilename();
//    String fileName = new Date()getTime()+"jpg";
    Systemoutprintln(path);
    File targetFile = new File(path, fileName);
    if(!targetFileexists()){
      targetFilemkdirs();
    }

    // save
    try {
      filetransferTo(targetFile);
    } catch (Exception e) {
      eprintStackTrace();
    }
    modeladdAttribute("fileUrl", requestgetContextPath()+"/upload/"+fileName);

    return "result";
  }

}

index.jsp

<%@ page pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> To upload pictures </title>
</head>
<body>
<form action="uploaddo" method="post" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="Submit" /></form>
</body>
</html>

WEB result. Under - INF/jsp/jsp

<%@ page pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Upload the result </title>
</head>
<body>
<img alt="" src="${fileUrl }" />
</body>
</html>