spring mvc -文件下載


1、下載一個E盤存在jpg文件   

 

【1】因為是spring-mvc 而且是文件上傳  ,所以需要導入以下包(可能會有多余,但是絕對夠用),核心jar包是(commons-io和commons-fileupload)

 

 

【2】編寫大配置文件applicationContext.xml

  <context:component-scan base-package="cn.happy.test"></context:component-scan>

【3】編寫上傳文件類

 

package cn.happy.test;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUp {
    
@RequestMapping("/download.do")  
public ResponseEntity<byte[]> download(String filename) throws IOException {  
    HttpHeaders headers = new HttpHeaders();  
    String file="E:\\"+filename;
    File file2 = new File(file);
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
    System.out.println(filename);
    String charset=new String(filename.getBytes("utf-8"),"iso-8859-1");
    headers.setContentDispositionFormData("file", charset);  
    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file2),  
                                      headers, HttpStatus.CREATED);  
}  
    
}

 

 在前台寫一個a標簽

<a href="${pageContext.request.contextPath }/download.do?filename=呵呵.jpg">下載</a>

web.xml配置

<!--編碼過濾器  -->
  <filter>
      <filter-name>characterEncoding</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      
      <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
      </init-param>
  </filter>
  
  <filter-mapping>
      <filter-name>characterEncoding</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  
  <!-- 配置中英調度器 -->
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>

 

 

直接拷貝就行

 


免責聲明!

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



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