在SpringMVC框架下實現文件的 上傳和 下載


在eclipse中的javaEE環境下:導入必要的架包

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">
  
     <!-- 配置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>
  
    <!-- 配置 HiddenHttpMethodFilter: 把 POST 請求轉為 DELETE、PUT 請求 -->
      <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>

 

spring的bean的配置文件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">
    
    <!-- 配置自動掃描的包 -->
    <context:component-scan base-package="com.atguigu.springmvc"></context:component-scan>
    
    <!-- 配置視圖解析器 -->
    <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-handler 將在 SpringMVC 上下文中定義一個 DefaultServletHttpRequestHandler,
        它會對進入 DispatcherServlet 的請求進行篩查, 如果發現是沒有經過映射的請求, 就將該請求交由 WEB 應用服務器默認的 
        Servlet 處理. 如果不是靜態資源的請求,才由 DispatcherServlet 繼續處理

        一般 WEB 應用服務器默認的 Servlet 的名稱都是 default.
        若所使用的 WEB 服務器的默認 Servlet 名稱不是 default,則需要通過 default-servlet-name 屬性顯式指定
        
    -->
    <mvc:default-servlet-handler/>
    
    <!-- 一般都會配置這個 <mvc:annotation-driven ></mvc:annotation-driven>,
    由於。。。requestmapping請求實現不了,使用這個,會使requestmapping請求一定實現
    -->
    <mvc:annotation-driven ></mvc:annotation-driven>

  <!-- 配置 MultipartResolver ,即配置文件上傳的屬性-->
  <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 默認的字符編碼 -->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!-- 上傳文件的大小 ,最大上傳大小-->
    <property name="maxUploadSize" value="1024000"></property>
  </bean>

</beans>

 

handler類方法:實現文件的上傳和下載的方法

@Controller
public class SpringMVCTest {
    
    @Autowired
    private EmployeeDao employeeDao;
    //實現文件的下載
    //需要說明的是文件的上傳和下載不需要其他配置
    @RequestMapping("testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
        
        byte[] body=null;
        ServletContext servletContext=session.getServletContext();
        ///files/abc.txt:所要下載文件的地址
        InputStream in=servletContext.getResourceAsStream("/files/abc.txt");
        body=new byte[in.available()];
        in.read(body);
        
        HttpHeaders headers=new HttpHeaders();
        //響應頭的名字和響應頭的值
        headers.add("Content-Disposition", "attachment;filename=abc.txt");
        
        HttpStatus statusCode=HttpStatus.OK;
        
        ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }

  //文件上傳,
    @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頁面: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>

  <!-- 文件上傳的表單 -->
  <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>
    
    <!-- 文件的下載 -->
    <a href="testResponseEntity">Test ResponseEntity</a>
    
    </center>
    
</body>
</html>

 

success.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>
    
    <h3>Success page</h3>
    
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM