码迷,mamicode.com
首页 > 编程语言 > 详细

java中一个简单的下载示例

时间:2015-04-04 18:22:10      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

首先在tomcat服务器下的webapps的download项目下建一个doc文件夹,再建个test.doc.防止控指针异常

技术分享

DownLoad.java代码

 1 package com.down;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.ServletOutputStream;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 @WebServlet(
14         name="download",
15         urlPatterns={"/test"}
16         )
17 public class DownLoad extends HttpServlet {
18     @Override
19     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
20             throws ServletException, IOException {
21         doGet(req, resp);
22     }
23     @Override
24     protected void doGet(HttpServletRequest request, HttpServletResponse response)
25             throws ServletException, IOException {
26         response.setContentType("application/msword");
27         response.addHeader("Content-disposition","attachment;filename=test.doc");
28         InputStream in=getServletContext().getResourceAsStream("/doc/test.doc");
29         ServletOutputStream os=response.getOutputStream();
30         byte[] bytes=new byte[1024];
31         int len=-1;
32         while((len=in.read(bytes))!=-1){
33             os.write(bytes,0,len);
34         }
35         in.close();
36         os.close();
37     }
38 }

运行结果:

技术分享

java中一个简单的下载示例

标签:

原文地址:http://www.cnblogs.com/guoyansi19900907/p/4392459.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!