• java 下载文件


     //servlet下载:根据请求url。拦截路径,读取服务器文件流,返回给浏览器,
     // 其中请求url可以通过request对象的getRequestURI()获取文件名(用来重命名文件)
    public class DownloadServlet extends HttpServlet
    {

     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
       throws ServletException, IOException
     {
      doPost(req, resp);
     }

     @Override
     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
       throws ServletException, IOException
     {

      String url = req.getRequestURI();
      String resFileName = url.substring(url.lastIndexOf("/")+1,url.length());
      String realPath = req.getRealPath("/");
      String exeFile = realPath + "download/test.exe";
      String kipFile = realPath + "download/exe";
      PrintWriter out = resp.getWriter();
      if (Tools.checkFileExist(exeFile, kipFile))
      {
       try
       {
        File f = new File(exeFile);
        BufferedInputStream buffer = new BufferedInputStream(
          new FileInputStream(f));
        byte[] bt = new byte[1024];
        int len = 0;
        resp.reset();

        resp.setContentType("application/x-msdownload");
        resp.setHeader("Content-Disposition", "attachment;filename="
          + resFileName);
        OutputStream out1 = resp.getOutputStream();
        while ((len = buffer.read(bt)) > 0)
        {
         out1.write(bt, 0, len);
        }
        buffer.close();
        out1.close();
                                    
       } catch (Exception e)
       {
        System.out.println("read downloadfile error:" + e);
       }

      } else
      {
       out.println("<center>file is not exsit!</center>");
      }
     }

    }

  • 相关阅读:
    测试如何发挥更大的价值?聊聊测试左移和右移
    Cocos Creator性能调优
    跨域问题产生的原因和解决方法
    tornado部署
    tonado
    MySQL binlog
    grpc
    nextjs中的懒加载
    前端低代码-少写代码实现灵活需求
    MySQL中的锁
  • 原文地址:https://www.cnblogs.com/qqzy168/p/2669009.html
Copyright © 2020-2023  润新知