下载文件如word,pdf文件等

本文介绍了一种通过Java Web应用程序实现的PDF文件下载方法。该方法利用了HTTPServletResponse来设置响应头并发送文件内容,实现了从服务器下载指定的PDF文件到客户端的功能。
 

 /**
  * 下载pdf
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws Exception
  */
 public ActionForward downnewYearPdf(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  byte[] buffer;
  InputStream ins;
  String dirPaths, filepath;
  try {
   // 工程类路径,用来获取保存文件的的路径
   String url = request.getSession().getServletContext().getRealPath(request.getRequestURI());
   int a = url.lastIndexOf(File.separator);
   url = url.substring(0, a);
   String name = "newyear.pdf";//文件名字
   filepath = "/newyear/newYear.pdf";//文件根目录下的路径
   dirPaths = url + filepath;//总路径
   try {
    // 读取文件
    if (!"".equals(dirPaths)) {
     ins = new FileInputStream(dirPaths);
     int bytesRead = 0;
     buffer = new byte[4096];
     response.setContentType("application/x-msdownload");
     response.setHeader("Content-Disposition", "attachment;"
       + " filename="
       + new String(name.getBytes(), "ISO-8859-1"));
     while ((bytesRead = ins.read(buffer, 0, 4096)) != -1) {
      try {
       response.getOutputStream().write(buffer);
       response.getOutputStream().flush();
      } catch (Exception ex) {
       throw new Exception("读数据流出现错误");
      }
     }
     buffer = null;
     response.getOutputStream();
     ins.close();
    }
   } catch (Exception ex) {
    request.setAttribute(Constants.C_ERROR_MSG, "“" + name
      + "文件不存在硬盘中“");
    return mapping.findForward("error");
   }

  } catch (Exception ex) {
   request.setAttribute(Constants.C_ERROR_MSG, "文件下载出现错误");
   return mapping.findForward("error");
  }
  return null;
 }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值