Http方式下载,Servlet实现

与普通的Servlet处理请求类似,浏览器端输入URL,该URLtomcat分配给相应的Servlet进行处理,以下为示例代码:

 1 public void service(HttpServletRequest req, HttpServletResponse res) {
2
3 File file = new File(fileName);
4 if(file.exists()) {
5 FileInputStream in = new FileInputStream(file);
6 try {
7 res.setContentType("application/zip");
8 res.setContentLength( (int)file.length() );
9 res.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
10 ServletOutputStream out = res.getOutputStream();
11 int read = 0;
12 byte buf[] = new byte[4096];
13 while ((read = in.read(buf, 0, 4096)) != -1)
14 {
15 out.write(buf, 0, read);
16 }
17 if (out != null)
18 {
19 out.close();
20 }
21 in.close();
22 file.delete();
23 } catch (IOException e) {
24 System.out.println(fileName+" 文件下载出错");
25 e.printStackTrace();
26 }
27 } else {
28 System.out.println(fileName+" 文件不存在");
29 }
30 }



 

posted on 2011-09-28 15:05  shosciation  阅读(272)  评论(0编辑  收藏  举报