SpringMVC實現文件下載


<br> public static void download(HttpServletRequest request, 
            HttpServletResponse response, String storeName, String contentType
           ) throws Exception { 
         
        request.setCharacterEncoding("UTF-8"); 
        BufferedInputStream bis = null; 
        BufferedOutputStream bos = null; 
   
        //獲取項目根目錄
        String ctxPath = request.getSession().getServletContext() 
                .getRealPath(""); 
         
        //獲取下載文件露肩
        String downLoadPath = ctxPath+"/uploadFile/"+ storeName; 
   
        //獲取文件的長度
        long fileLength = new File(downLoadPath).length(); 
 
        //設置文件輸出類型
        response.setContentType("application/octet-stream"); 
        response.setHeader("Content-disposition", "attachment; filename=" 
                + new String(storeName.getBytes("utf-8"), "ISO8859-1"));
        //設置輸出長度
        response.setHeader("Content-Length", String.valueOf(fileLength)); 
        //獲取輸入流
        bis = new BufferedInputStream(new FileInputStream(downLoadPath)); 
        //輸出流
        bos = new BufferedOutputStream(response.getOutputStream()); 
        byte[] buff = new byte[2048]; 
        int bytesRead; 
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { 
            bos.write(buff, 0, bytesRead); 
        } 
        //關閉流
        bis.close(); 
        bos.close(); 
    } 
復制代碼

下載直接訪問控制器如:http:\\localhost:8080/springmvc/download.do

 或者通過JSP頁面

<a href="./downloadFile/download" >下載</a> 


免責聲明!

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



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