JSP实现文件下载代码

本文介绍了一种使用JSP技术实现文件下载的方法。通过设置HTTP响应头并利用Servlet读取文件内容来完成文件的下载过程。该示例代码展示了如何指定下载文件名及路径,并通过流操作将文件发送给客户端。
JSP实现文件下载代码
<%
       String path=request.getContextPath();
%>
<title>login.jsp</title>
<body>
    <a href="<%=path %>/Download.jsp">download</a>
</body>
<title>Download.jsp</title>
  <body>
    <%
      response.setContentType("application/x-download");
      String filedownload="f:/稿子.ppt";
      String filedisplay = "演示文稿.ppt";
      String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
      response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
      OutputStream outp = null;
      FileInputStream in = null;
      try
      {
          outp = response.getOutputStream();
          in = new FileInputStream(filedownload);
          byte[] b = new byte[1024];
          int i = 0;
          while((i = in.read(b)) > 0)
          {
              outp.write(b, 0, i);
          }
          outp.flush();
      }
      catch(Exception e)
      {
          System.out.println("Error!");
          e.printStackTrace();
      }
      finally
      {
          if(in != null)
          {
              in.close();
              in = null;
          }
          if(outp != null)
          {
              outp.close();
              outp = null;
          }
      }
%>
  </body>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值