1. 程式人生 > >servlet中的檔案下載

servlet中的檔案下載

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/**
		 * 使用OutputStream流向客戶端瀏覽器輸出中文資料(檔案下載)
		 * 以上內容只能開啟檔案,卻不能儲存到相應的目錄位置
		 *  檔案下載功能是web開發中經常使用到的功能,使用HttpServletResponse物件就可以實現檔案的下載
		 * getOutputStream():向客戶端傳送資料(位元組流)
		 * getWriter():向客戶端傳送資料(字元流)
		 */
//1.獲取要下載的檔案的絕對路徑 String path = request.getServletContext().getRealPath("/1.jpg"); //2.獲取要下載的檔名 String fileName = path.substring(path.lastIndexOf("\\")+1); //3.設定content-disposition響應頭控制瀏覽器以下載的形式開啟檔案 //設定context-disposition響應頭,控制瀏覽器以下載形式開啟,這裡注意檔案字符集編碼格式,設定utf-8,不然會出現亂碼 response.setHeader("content-disposition"
,"attachment;filename="+URLEncoder.encode(fileName,"UTF-8")); //4.獲取要下載的檔案輸入流 //字元流輸入流FileReader in = new FileReader(path); InputStream in=new FileInputStream(path); int len=0; //5.建立資料緩衝區 //字元流緩衝區:char[] buffer = new char[1024]; byte[] buffer = new byte[1024]; //6.通過response物件獲取OutputStream流 //編寫檔案下載功能時推薦使用OutputStream流,避免使用PrintWriter流,
//因為OutputStream流是位元組流,可以處理任意型別的資料, //而PrintWriter流是字元流,只能處理字元資料,如果用字元流處理位元組資料,會導致資料丟失 //字元流寫入流:PrintWriter out = response.getWriter(); ServletOutputStream out = response.getOutputStream(); //7.將FileInputStream流寫入到buffer緩衝區 while((len=in.read(buffer))!=-1){ //8.使用OutputStream將緩衝區的資料輸出到客戶端瀏覽器 out.write(buffer, 0, len); } in.close(); }