servlet實現檔案下載demo

十五樓亮哥發表於2015-02-04
一:web.xml配置servlet入口
<span style="font-size:18px;"><strong>       <servlet>
	   <servlet-name>DownLoadAttachmentServlet</servlet-name>
	    <servlet-class>com.bright.servlet.DownLoadAttachmentServlet</servlet-class>
	</servlet>
	<servlet-mapping>
	   <servlet-name>DownLoadAttachmentServlet</servlet-name>
	   <url-pattern>/downloadAttachment.do</url-pattern>
	</servlet-mapping>
	</strong></span>


二:Servlet實現 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

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

import com.bright.resource.action.ArticleAction;
import com.bright.resource.entity.Article;
import com.bright.util.PropsUtil;

/**
 * @author Administrator
 *
 */
public class DownLoadAttachmentServlet extends HttpServlet{
	private static final long serialVersionUID = -1273430545946412812L;
	
	
	@Override
	public void init(){
		System.out.println("---------------------init");
	}
	
	

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		try{
		System.out.println("----------------------------doGet");
		resp.setContentType("text/html;charset=UTF-8");
		PrintWriter out = resp.getWriter();
		out.print("Hello 大家好");
		out.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse response) throws IOException {
		String articleId = req.getParameter("articleId");
		ArticleAction action = new ArticleAction();
		Article article = null;
		try {
		   article = action.getArticleById(Long.parseLong(articleId));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
		 //建立要下載的檔案的物件(引數為要下載的檔案在伺服器上的路徑)  
		String path = PropsUtil.property("localResourceDir")+article.getUrlAttachment()+"/"+article.getAttachmentFilename();
        File serverFile=new File(path);  
          
        //設定要顯示在儲存視窗的檔名,如果檔名中有中文的話,則要設定字符集,否則會出現亂碼。另外,要寫上檔案字尾名  
        String fileName = java.net.URLEncoder.encode(article.getAttachmentFilename(),"utf-8");  
        //該步是最關鍵的一步,使用setHeader()方法彈出"是否要儲存"的對話方塊,打引號的部分都是固定的值,不要改變  
        response.setHeader("Content-disposition","attachment;filename="+fileName);  
         
        /* 
         * 以下四行程式碼經測試似乎可有可無,可能是我測試的檔案太小或者其他什麼原因。。。 
         */  
        response.setContentType("application/msword");  
        //定義下載檔案的長度 /位元組  
        long fileLength=serverFile.length();  
        //把長整形的檔案長度轉換為字串  
        String length=String.valueOf(fileLength);  
        //設定檔案長度(如果是Post請求,則這步不可少)  
        response.setHeader("content_Length",length);  
          
        /* 
         *以上內容僅是下載一個空檔案 
         *以下內容用於將伺服器中相應的檔案內容以流的形式寫入到該空檔案中 
         */  
        //獲得一個 ServletOutputStream(向客戶端傳送二進位制資料的輸出流)物件  
        OutputStream servletOutPutStream=response.getOutputStream();  
        //獲得一個從伺服器上的檔案myFile中獲得輸入位元組的輸入流物件  
        FileInputStream fileInputStream=new FileInputStream(serverFile);  
          
          
        byte bytes[]=new byte[1024];//設定緩衝區為1024個位元組,即1KB  
        int len=0;  
        //讀取資料。返回值為讀入緩衝區的位元組總數,如果到達檔案末尾,則返回-1  
        while((len=fileInputStream.read(bytes))!=-1)  
        {     
            //將指定 byte陣列中從下標 0 開始的 len個位元組寫入此檔案輸出流,(即讀了多少就寫入多少)  
            servletOutPutStream.write(bytes,0,len);   
        }  
          
        servletOutPutStream.close();  
        fileInputStream.close();  

	}
	
	@Override
	public void destroy() {
		super.destroy();
		System.out.println("----------------------------destroy");

	}
}


三:呼叫方式  XXXX/downloadAttachment.do注意用post方式提交

相關文章