首页 > 学院 > 开发设计 > 正文

java中一个简单的下载示例

2019-11-14 23:38:11
字体:
来源:转载
供稿:网友
java中一个简单的下载示例 Posted on 2015-04-04 17:10 思思博士 阅读(...) 评论(...) 编辑 收藏

首先在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     @Override19     PRotected void doPost(HttpServletRequest req, HttpServletResponse resp)20             throws ServletException, IOException {21         doGet(req, resp);22     }23     @Override24     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 }

运行结果:


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表