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>");
  }
 }

}

你可能感兴趣的:(java)