servlet實現下載功能

dxm809發表於2020-09-26
package com.itheima.content;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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;

import sun.misc.BASE64Encoder;

public class DownLoadServlet2 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//*******檔名稱是中文的下載*******


		//獲得要下載的檔案的名稱
		String filename = request.getParameter("filename");//????.jpg
		//解決獲得中文引數的亂碼----下節課講
		filename = new String(filename.getBytes("ISO8859-1"),"UTF-8");//美女.jpg

		
		//獲得請求頭中的User-Agent
		String agent = request.getHeader("User-Agent");
		//根據不同瀏覽器進行不同的編碼
		String filenameEncoder = "";
		if (agent.contains("MSIE")) {
			// IE瀏覽器
			filenameEncoder = URLEncoder.encode(filename, "utf-8");
			filenameEncoder = filenameEncoder.replace("+", " ");
		} else if (agent.contains("Firefox")) {
			// 火狐瀏覽器
			BASE64Encoder base64Encoder = new BASE64Encoder();
			filenameEncoder = "=?utf-8?B?"
					+ base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
		} else {
			// 其它瀏覽器
			filenameEncoder = URLEncoder.encode(filename, "utf-8");				
		}



		//要下載的這個檔案的型別-----客戶端通過檔案的MIME型別去區分型別
		response.setContentType(this.getServletContext().getMimeType(filename));
		//告訴客戶端該檔案不是直接解析 而是以附件形式開啟(下載)----filename="+filename 客戶端預設對名字進行解碼
		response.setHeader("Content-Disposition", "attachment;filename="+filenameEncoder);

		//獲取檔案的絕對路徑
		String path = this.getServletContext().getRealPath("download/"+filename);
		//獲得該檔案的輸入流
		InputStream in = new FileInputStream(path);
		//獲得輸出流---通過response獲得的輸出流 用於向客戶端寫內容
		ServletOutputStream out = response.getOutputStream();
		//檔案拷貝的模板程式碼
		int len = 0;
		byte[] buffer = new byte[1024];
		while((len=in.read(buffer))>0){
			out.write(buffer, 0, len);
		}

		in.close();
		//out.close();

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

 

相關文章