首页 > 代码库 > 用serlet实现文件下载

用serlet实现文件下载

原文http//blog_sina_com_cn/s/blog_49a269ae01008yv2.html


之前没怎么用过这个,这次项目中用到了,于是总结一下:

应该说主要注意三方面:

1、写一个servlet

2、在web.xml中配置这个servlet

3、页面上调用这个servlet

 

第一:

写一个servlet,当然要继承javax.servlet.http.HttpServlet,重写post或者get方法(看需要),这个servlet的思想就是将要下载的文件写到文件流中去,而这个文件输出流就是HttpServletResponse对象的输出流,如下所示:

public class DownloadServlet extends HttpServlet{
 
 
 public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
 {
  try
  {
   String downFilename=request.getParameter("curfile");
   String filepath=request.getParameter("path");
        response.setContentType("text/plain");
        response.setHeader("Location",downFilename);
        response.setHeader("Content-Disposition", "attachment; filename=" + downFilename);
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = new FileInputStream(filepath+downFilename);
        byte[] buffer = new byte[1024];
        int i = -1;
        while ((i = inputStream.read(buffer)) != -1) {
         outputStream.write(buffer, 0, i);
        }
        outputStream.flush();
        outputStream.close();
  }catch(FileNotFoundException e1)
  {
   System.out.println("没有找到您要的文件");
  }
  catch(Exception e)
  {
   System.out.println("系统错误,请及时与管理员联系");
  }
    }
 
 
 public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
 {
  doPost(request,response);
 }

}

 

web.xml配置:

<servlet>
  <servlet-name>download</servlet-name>
  <servlet-class>com.dichain.common.tools.DownloadServlet</servlet-class>
 </servlet>

<servlet-mapping>
  <servlet-name>download</servlet-name>   
  <url-pattern>/Download</url-pattern>
 </servlet-mapping>

 

jsp中调用servlet弹出一个下载对话框:

window.open (‘Download?curfile=‘+curfile+‘&path=‘+path,‘newwindow‘,‘height=30,width=40,top=‘+yy+‘,left=‘+xx+‘,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no‘);


用serlet实现文件下载