java實現檔案的下載的方法概述

zybing發表於2021-09-09
 /** 
     * 下載  realName:檔名
     */  
    public static void download(HttpServletRequest request,HttpServletResponse response,String realName) throws Exception {  
        response.setContentType("application/zip");  
        //設定內容作為附件下載  fileName有字尾,比如1.jpg  
        response.setHeader("Content-Disposition", "attachment; filename="+realName); 
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
        String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "uploadfile/";  
        String downLoadPath = ctxPath+realName;  
        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();  
    } 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/855/viewspace-2799690/,如需轉載,請註明出處,否則將追究法律責任。

相關文章