首先在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 }
运行结果: