Spring Boot 文件下載


1. 文件下載類

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class DownloadUtil {

    public boolean fileDownload(HttpServletResponse response,String filePath,String fileName)
        throws UnsupportedEncodingException {
        
        File file = new File(filePath);//創建下載的目標文件,參數為文件的真實路徑
        if(file.exists()){ //判斷文件是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(fileName,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件輸入流
            BufferedInputStream bis = null;

            OutputStream os = null; //輸出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

 

2. 文件下載a標簽

<a th:href="@{/download/} + ${fileName}+'?filePath='+${filePath}">點擊下載文件</a>

filePath為文件的真實路徑,由於路徑的符號與RESTful API風格沖突,所以采取傳統a標簽的傳參方式

 

3. 控制器

/**
     * 測試文件下載
     * @param fileName
     * @param filePath
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
@GetMapping("/download/{fileName}")
public String testDownload(@PathVariable("fileName") String fileName,String filePath,HttpServletResponse response) throws UnsupportedEncodingException {

    System.out.println("==>開始文件下載!");

    DownloadUtil downloadUtil = new DownloadUtil();

    downloadUtil.fileDownload(response,filePath,fileName);

    return null;
}

 


免責聲明!

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



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