首页 > 技术文章 > java 的在线下载文件 .pdf

zhukaixin 2018-06-07 15:56 原文

 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 }

 

 自己之前没有做过在线现在的  项目中用到了  就让大神发了一份代码  看了看  自己研究一下                       

 

推荐阅读