使用Servlet實現下載文件的功能

在前臺有一個下載連接,好比html

 

<a href="DownLoadServlet">下載</a> <br/>  

 


使用Servlet實現下載:html5

 

 

import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.net.URLEncoder;  
  
import javax.servlet.ServletException;  
import javax.servlet.ServletOutputStream;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
public class DownLoadServlet extends HttpServlet {  
  
      
    public DownLoadServlet() {  
        super();  
    }  
  
  
    public void destroy() {  
        super.destroy(); // Just puts "destroy" string in log  
        // Put your code here  
    }  
  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doPost(request,response);  
    }  
  
      
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        //處理請求  
        //讀取要下載的文件  
        File f = new File("E:/很久不見.mp3");  
        if(f.exists()){  
            FileInputStream  fis = new FileInputStream(f);  
            String filename=URLEncoder.encode(f.getName(),"utf-8"); //解決中文文件名下載後亂碼的問題  
            byte[] b = new byte[fis.available()];  
            fis.read(b);  
            response.setCharacterEncoding("utf-8");  
            response.setHeader("Content-Disposition","attachment; filename="+filename+"");  
            //獲取響應報文輸出流對象  
            ServletOutputStream  out =response.getOutputStream();  
            //輸出  
            out.write(b);  
            out.flush();  
            out.close();  
        }     
          
    }  
  
    /** 
     * Initialization of the servlet. <br> 
     * 
     * @throws ServletException if an error occurs 
     */  
    public void init() throws ServletException {  
        // Put your code here  
    }  
  
}  

 

 

 

配置文件注意路徑。。。java

 

 

本文來源於 :http://www.cnblogs.com/android-html5/archive/2012/03/16/2534082.htmlandroid

相關文章
相關標籤/搜索