English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example of file upload and download under the SpringMVC framework

Import the necessary packages in the javaEE environment of eclipse:

The configuration file of web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
id="WebApp_ID" version="2.5">
   <!-- Configure the SpringMVC DispatcherServlet -->
  <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- Configure HiddenHttpMethodFilter: Convert POST requests to DELETE, PUT requests -->
   <filter>
     <filter-name>HiddenHttpMethodFilter</filter-name>
     <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
   </filter>
   <filter-mapping>
     <filter-name>HiddenHttpMethodFilter</filter-name>
     <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app> 

The configuration file for spring's beans is springmvc.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:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.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-4.0.xsd">
  <!-- Configure the package for automatic scanning -->
  <context:component-scan base-package="com.atguigu.springmvc"></context:component-scan>
  <!-- Configure the view resolver -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/></property>
    <property name="suffix" value=".jsp"></property>
  </bean>
  <!-- 
    default-servlet-The handler will define a DefaultServletHttpRequestHandler in the SpringMVC context.
    It will screen the requests entering the DispatcherServlet, if it finds that the request has not been mapped, it will hand over the request to the defaultServlet of the WEB application server 
    Servlet processing. If it is not a static resource request, it will be processed by DispatcherServlet
    The default Servlet name of most WEB application servers is default.
    If the default Servlet name of the WEB server used is not default, it needs to be passed through default-servlet-The name attribute explicitly specifies
  -->
  <mvc:default-servlet-handler/>
  <!-- It is generally configured with this <mvc:annotation-driven ></mvc:annotation-driven> ,
  Since the requestmapping request cannot be implemented, this is used, which will ensure that the requestmapping request is implemented
  -->
  <mvc:annotation-driven ></mvc:annotation-driven> 
  <!-- Configure MultipartResolver, that is, configure the properties of file upload-->
   <bean id="multipartResolver" 
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- Default character encoding -->
    <property name="defaultEncoding" value="UTF-8></property> 
    <!-- The size of the uploaded file, maximum upload size-->
    <property name="maxUploadSize" value="1024000"></property>
   </bean>
 </beans> 

 Handler class method: methods for implementing file upload and download

 @Controller
public class SpringMVCTest {
  @Autowired
  private EmployeeDao employeeDao;
  //Implementation of file download
  //It should be noted that file upload and download do not require other configuration
  @RequestMapping("testResponseEntity")
  public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
    byte[] body=null;
    ServletContext servletContext=session.getServletContext();
    ///files/abc.txt: the address of the file to be downloaded
    InputStream in=servletContext.getResourceAsStream("/files/abc.txt");
    body=new byte[in.available()];
    in.read(body);
    HttpHeaders headers=new HttpHeaders();
    //The name and value of the response header
    headers.add("Content-Disposition", "attachment;filename=abc.txt");
    HttpStatus statusCode=HttpStatus.OK;
    ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
    return response;
  } 
  //File upload,
     @RequestMapping("/testFileUpload)
     public String testFileUpload(@RequestParam("desc") String desc,
      @RequestParam("file") MultipartFile file) throws IOException{
      System.out.println("desc:"+desc);
      System.out.println("OriginalFilename"+file.getOriginalFilename());
      System.out.println("InputStream"+file.getInputStream());
      return "success";
   }
 } 

jsp page: index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <center> 
  <!-- The form for file upload -->
   <form action="testFileUpload" method="post" enctype="multipart/form-data">
    File:<input type="file" name="file"/>
    Desc:<input type="text" name="desc"/>
    <input type="submit" value="Submit"/>
   </form>
   <br><br>
  <!-- File download -->
  <a href="testResponseEntity" rel="external nofollow" >Test ResponseEntity</a>
  </center>
</body>
</html> 

success.jsp page: Display file upload success

 <%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <h3>Success page</h3>
</body>
</html>

That's all for this article. I hope it will be helpful to everyone's learning and that everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like