java实现文件下载

java 专栏收录该内容
30 篇文章 0 订阅

/**
    该类使用方法:
    在使用struts框架(或其他框架)时,如果从action转到该servlet,有一点要注意。就是在使action之前如果是用了filter,并且在filter调用了getWriter()方法,那么action跳转到该servlet时,必须是redirect形式,否则会出错。出错信息大致如下:
    java.lang.IllegalStateException: getWriter() has already been called for this re
    sponse。
    
    该类的两个假设:
    1。假使下载的文件名传送到该servlet的名字是“filename”。使用redirect到本servlet时,参数传送可以通过session;
    2。假使要下载的文件在目录“rootpath”下。
    
    **/
    public class DownloadFile extends HttpServlet {
    
     public String getValue(HttpServletRequest request, String name) {
     String value = null;
     value = request.getParameter(name);
     if (value != null)
     return value;
     value = (String) request.getAttribute(name);
     if (value != null)
     return value;
     value = (String) request.getSession().getAttribute(name);
     request.getSession().removeAttribute(name);
     return value;
     }
    
     public void doPost(HttpServletRequest request, HttpServletResponse response) {
     FileInputStream fis = null;
     ServletOutputStream fout = null;
     try {
     String filename = getValue(request, "filename");
     if (filename != null) {
     String oldcharset = request.getCharacterEncoding();
     String showFilename = null;
     if (oldcharset != null) {
     showFilename = new String(filename.getBytes(request
     .getCharacterEncoding()), "ISO_8859_1");
     } else {
     showFilename = new String(filename.getBytes(), "ISO_8859_1");
     }
     String rootpath = getValue(request, "rootpath");   if (rootpath == null) {
     rootpath = getServletContext().getRealPath("/");
     }
     String filepath = rootpath + filename;
     response.reset();
     response.setHeader("Pragma", "No-cache");
     response.setHeader("Cache-Control", "no-cache");
     response.setDateHeader("Expires", 0);
     response.setContentType("application/octet-stream;charset=GBK");
     response.setHeader("Content-disposition",
     "attachment;filename=/"" + showFilename + "/"");
     fis = new FileInputStream(filepath);
     fout = response.getOutputStream();
     int byteRead;
     while ((byteRead = fis.read()) != -1) {
     fout.write(byteRead);
     }
     }
     } catch (Exception e) {
     e.printStackTrace();
     } finally {
     if (fis != null) {
     try {
     fis.close();
     } catch (IOException e) {
     }
     }
     if (fout != null) {
     try {
     fout.close();
     } catch (IOException e) {
     }
     }
     }
     }
    
     public void doGet(HttpServletRequest request, HttpServletResponse response) {
     doPost(request, response);
     }
    } 
 

  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值