java之 檔案下載筆記
阿新 • • 發佈:2019-02-18
1:必須有一個form 作為接收的容器
接下來看我的js 程式碼:
2:控制器程式碼:
String filename = map.get("name").toString(); response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("UTF-8"); // 獲取路徑 String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "\\" + "upload\\"; String downLoadPath = ctxPath + filename; // 建立file物件 File file = new File(downLoadPath); if (file.exists()) { // 寫明要下載的檔案的大小 response.setContentLength((int) file.length()); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(file.getName(),"UTF-8")); }else{ response.setStatus(404); } // 讀出檔案到i/o流 FileInputStream fis = new FileInputStream(file); BufferedInputStream buff = new BufferedInputStream(fis); byte[] b = new byte[1024];// 相當於我們的快取 long k = 0;// 該值用於計算當前實際下載了多少位元組 // 從response物件中得到輸出流,準備下載 OutputStream myout = response.getOutputStream(); // 開始迴圈下載 while (k < file.length()) { int j = buff.read(b, 0, 1024); k += j; // 將b中的資料寫到客戶端的記憶體 myout.write(b, 0, j); } // 將寫入到客戶端的記憶體的資料,重新整理到磁碟 myout.flush(); logger.debug("upload over"); return null;
接下來看我的js 程式碼:
//下載
function f_download(name){
$("#name").val(name);
var form = $("#download");
form.attr("action","BsthJdJypxjlb/download.do");
form.submit();
}