查看: 2416|回复: 0

[Java语言] 追加java实现文件下载的方法

发表于 2018-1-18 08:00:02

下载压缩包

  1. //realName为要下载文件的名称
  2. public static void downloadStore(HttpServletRequest request,HttpServletResponse response,String realName) throws Exception {
  3. BufferedInputStream bis = null;
  4. BufferedOutputStream bos = null;
  5. String ctxPath = request.getSession().getServletContext().getRealPath("/")+ FileOperateUtil.UPLOADDIR+"chainCompany/";
  6. String downLoadPath = ctxPath+realName;
  7. response.reset();
  8. response.setContentType("application/zip");// 定义输出类型
  9. response.setHeader("Content-disposition", "attachment; filename=" + realName);
  10. bis = new BufferedInputStream(new FileInputStream(downLoadPath));
  11. bos = new BufferedOutputStream(response.getOutputStream());
  12. byte[] buff = new byte[2048];
  13. int bytesRead;
  14. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  15. bos.write(buff, 0, bytesRead);
  16. }
  17. bis.close();
  18. bos.close();
  19. }
复制代码

下载文件

  1. /**
  2. * 下载
  3. *realName为要下载文件的名称
  4. */
  5. public static void download(HttpServletRequest request,HttpServletResponse response,String realName) throws Exception {
  6. BufferedInputStream bis = null;
  7. BufferedOutputStream bos = null;
  8. //ctxPath 下载文件的路径
  9. String ctxPath = request.getSession().getServletContext().getRealPath("/")+
  10. FileOperateUtil.UPLOADDIR;
  11. String downLoadPath = ctxPath+realName;
  12. response.reset();
  13. response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
  14. response.setHeader("Content-disposition", "attachment; filename=" + realName);
  15. bis = new BufferedInputStream(new FileInputStream(downLoadPath));
  16. bos = new BufferedOutputStream(response.getOutputStream());
  17. byte[] buff = new byte[2048];
  18. int bytesRead;
  19. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  20. bos.write(buff, 0, bytesRead);
  21. }
  22. bis.close();
  23. bos.close();
  24. }
复制代码


回复

使用道具 举报