现在的位置: 首页 > 综合 > 正文

servlet实现文件下载

2013年06月22日 ⁄ 综合 ⁄ 共 1561字 ⁄ 字号 评论关闭

/*
 * Created on 2005-7-10
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.first.ticss.common;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jacky
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Download extends HttpServlet {

 public void init(ServletConfig config) throws ServletException {
  super.init(config);
  //TODO Method stub generated by Lomboz
 }

 public void destroy() {
  super.destroy();
  //TODO Method stub generated by Lomboz
 }

 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  
  String root = getServletContext().getRealPath("/");
     String path = request.getParameter("path");
     String name = request.getParameter("name");

     response.setContentType("text/x-msdownload");
     response.addHeader("Content-Disposition","attachment; filename=\"" + name + "\"");
    
     try
     {
         java.io.OutputStream    os  = response.getOutputStream();
         java.io.FileInputStream fis = new java.io.FileInputStream(root + path + name);
        
         byte[] b = new byte[1024];
         int    i = 0;
        
         while ( (i = fis.read(b)) > 0 )
         {
             os.write(b, 0, i);
         }
        
         fis.close();
         os.flush();
         os.close();
     }
     catch ( Exception e )
     {
      e.printStackTrace();
     }
  
 }
}
绝对得行,弄了一天才搞定!

抱歉!评论已关闭.