標籤:write 設定 font ati out resources 擷取 tco stream
java 的線上下載檔案 .pdf
1.下載資源的本地位置
2.設定回應標頭
3.下載代碼
1 PeriodicalResource periodicalResource = periodicalResourceService.get(id); 2 String filePath = periodicalResource.getAttachment();//擷取資源位置 3 File file = new File(periodicalBaseDir + filePath);//本地資源位置 4 if (file.exists()) { 5 response.setContentType("application/force-download");// 設定強制下載不開啟 6 response.addHeader("Content-Disposition", 7 "attachment;fileName=" + filePath.split("/")[filePath.split("/").length-1]);// 設定檔案名稱 8 byte[] buffer = new byte[1024]; 9 FileInputStream fis = null;10 BufferedInputStream bis = null;11 try {12 fis = new FileInputStream(file);13 bis = new BufferedInputStream(fis);14 OutputStream os = response.getOutputStream();15 int i = bis.read(buffer);16 while (i != -1) {17 os.write(buffer, 0, i);18 i = bis.read(buffer);19 }20 } catch (Exception e) {21 e.printStackTrace();22 } finally {23 if (bis != null) {24 try {25 bis.close();26 } catch (IOException e) {27 e.printStackTrace();28 }29 }30 if (fis != null) {31 try {32 fis.close();33 } catch (IOException e) {34 e.printStackTrace();35 }36 }37 }38 }
自己之前沒有做過線上現在的 項目中用到了 就讓大神發了一份代碼 看了看 自己研究一下
java 的線上下載檔案 .pdf