java web服務器文件的下載(有下載彈出匡)


昨天做了一個文件從服務下載的功能,怎么都不彈出頁面,下載框。后查詢得知。目前兩種方法

1.<a href='下載路徑' />

2.window.location.href = basePath + "downloadTemplate.do?template=huiyuan";

通過 這兩種方式可以有這種彈出窗

希望能幫助,遇到和我一樣問題的朋友~

 

 

附下載的工具類,可直接復制可用

public void downloadFile(String filePath,String fileName,HttpServletResponse response) throws Exception{
        //URI uri =  this.getClass().getClassLoader().getResource(filePath).toURI();
        File file = new File(filePath);
        // 清空response
        response.reset();
        // 設置response的Header
        response.addHeader("Content-Disposition", "attachment;filename="
                + new String(fileName.getBytes("gbk"), "iso-8859-1")); // 轉碼之后下載的文件不會出現中文亂碼
        response.addHeader("Content-Length", "" + file.length());
        // 以流的形式下載文件
        
        InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        OutputStream toClient = new BufferedOutputStream( response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
       }


免責聲明!

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



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