文件下载

  1. package com.lsgjzhuwei.servlet.response;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8.   
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.annotation.WebServlet;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. /** 
  16.  * Servlet implementation class ServletDownload 
  17.  */  
  18. @WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" })  
  19. public class ServletDownload extends HttpServlet {  
  20.     private static final long serialVersionUID = 1L;  
  21.          
  22.     /** 
  23.      * @see HttpServlet#HttpServlet() 
  24.      */  
  25.     public ServletDownload() {  
  26.         super();  
  27.         // TODO Auto-generated constructor stub  
  28.     }  
  29.   
  30.     /** 
  31.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
  32.      */  
  33.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  34.         // TODO Auto-generated method stub  
  35.           
  36.         //获得请求文件名  
  37.         String filename = request.getParameter("filename");  
  38.         System.out.println(filename);  
  39.           
  40.         //设置文件MIME类型  
  41.         response.setContentType(getServletContext().getMimeType(filename));  
  42.         //设置Content-Disposition  
  43.         response.setHeader("Content-Disposition", "attachment;filename="+filename);  
  44.         //读取目标文件,通过response将目标文件写到客户端  
  45.         //获取目标文件的绝对路径  
  46.         String fullFileName = getServletContext().getRealPath("/download/" + filename);  
  47.         //System.out.println(fullFileName);  
  48.         //读取文件  
  49.         InputStream in = new FileInputStream(fullFileName);  
  50.         OutputStream out = response.getOutputStream();  
  51.           
  52.         //写文件  
  53.         int b;  
  54.         while((b=in.read())!= -1)  
  55.         {  
  56.             out.write(b);  
  57.         }  
  58.           
  59.         in.close();  
  60.         out.close();  
  61.     }  
  62.   
  63.     /** 
  64.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
  65.      */  
  66.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  67.         // TODO Auto-generated method stub  
  68.     }  
  69.   

posted on 2017-12-05 18:32  admingy  阅读(152)  评论(0编辑  收藏  举报

导航