檔案下載,通過<a href="url">也是可以的,但是這樣直接下載,一般檔案名稱就是伺服器端的沒有任何意義的檔案名稱。
今天自己用到了另外一種,先說需求:1.檔案伺服器與系統沒有在同一伺服器,所以需要使用網路地址來進行下載;
2.上傳時為了避免檔案重名,使用uuid來產生了檔案名稱,真實的檔案名稱存與資料庫中;
3.所有的檔案都只能下載,不可直接在瀏覽器上開啟。
根據代碼來分析:這裡使用的springmvc
[java] view plain copy print ? @RequestMapping("/download") public String downloadAmachment(String downloadUrl, String realFileName, HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html;charset=UTF-8"); try { request.setCharacterEncoding("UTF-8"); BufferedInputStream bis = null; BufferedOutputStream bos = null; //此處使用的設定檔裡面取出的檔案伺服器位址,拼湊成完整的檔案伺服器上的檔案路徑 //寫demo時,可以直接寫成http://xxx/xx/xx.txt.這種形式 String downLoadPath = ConfigHelper.getString("img.server.url") + downloadUrl; response.setContentType("application/octet-stream"); response.reset();//清除response中的緩衝 //根據網路檔案地址建立URL URL url = new URL(downLoadPath); //擷取此路徑的串連 URLConnection conn = url.openConnection(); Long fileLength = conn.getContentLengthLong();//擷取檔案大小 //設定reponse回應標頭,真實檔案名稱重新命名,就是在這裡設定,設定編碼 response.setHeader("Content-disposition", "attachment; filename=" + new String(realFileName.getBytes("utf-8"), "ISO8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(conn.getInputStream());//構造讀取流 bos = new BufferedOutputStream(response.getOutputStream());//構造輸出資料流 byte[] buff = new byte[1024]; int bytesRead; //每次讀取緩衝大小的流,寫到輸出資料流 while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } response.flushBuffer();//將所有的讀取的流返回給用戶端 bis.close(); bos.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); return ErrorPages._500; } return