文件下载代码模板

 1 public void downloadAppliForm(String id, HttpServletRequest request,
 2             HttpServletResponse response) throws Exception {  //传入id,向数据库查询文件保存地址和文件名称      
 3         JgVolunteers jgVolunteers = jgVolunteersMapper.selectByPrimaryKey(Long
 4                 .valueOf(id));
 5         String fileName = null;
 6         String fileUrl = null;
 7         if (jgVolunteers != null) {
 8             fileName = jgVolunteers.getApplicationname(); //文件名称 文件名+文件类型
 9             fileUrl = VocationJunGangConstant.GYYJ_IMG_PATH+
10                     jgVolunteers.getUrldecode();//文件在服务器的保存地址
11         }
12         response.setContentType("text/html;charset=utf-8");
13         request.setCharacterEncoding("UTF-8");
14         java.io.BufferedInputStream bis = null;
15         java.io.BufferedOutputStream bos = null;
16 
17         try {
18             long fileLength = new File(fileUrl).length();
19             response.setContentType("application/x-msdownload;");
20             response.setHeader("Content-Disposition", "attachment; filename="
21                     + new String(fileName.getBytes("gbk"), "iso-8859-1"));
22             response.setHeader("Content-Length", String.valueOf(fileLength));
23             bis = new BufferedInputStream(new FileInputStream(fileUrl));
24             bos = new BufferedOutputStream(response.getOutputStream());
25             byte[] buff = new byte[2048];
26             int bytesRead;
27             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
28                 bos.write(buff, 0, bytesRead);
           bos.flush(); 
29 } 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } finally { 33 if (bis != null) 34 bis.close(); 35 if (bos != null) 36 bos.close(); 37 } 38 39 }

posted @ 2017-07-10 09:57  颜丑文良  阅读(293)  评论(0编辑  收藏  举报