標籤:protected 頭資訊 attach utf-8 class tcl new prot png
下面的代碼簡單的實現了java下載檔案的步驟,看代碼:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //擷取檔案的類名 String Path=this.getClass().getResource("/").getPath()+"JAVA筆記.txt"; //對擷取的路徑進行解碼 Path=URLDecoder.decode(Path); //擷取檔案名稱字和副檔名 String FileName=Path.substring(Path.lastIndexOf("/")+1,Path.length()); //設定輸出檔案名編碼 FileName=URLEncoder.encode(FileName, "UTF-8"); //設定頭資訊 response.setHeader("content-disposition", "attachment;filename="+FileName); response.setContentType("application/octet-stream"); //擷取檔案流對象 FileInputStream file=new FileInputStream(Path); //定義位元組數組,長度為檔案流的長度 byte[] buffers=new byte[file.available()]; //擷取輸出資料流對象 OutputStream writer=response.getOutputStream(); //把流輸出到位元組數組中去 file.read(buffers); //寫到頁面 writer.write(buffers); //關閉流 writer.close(); file.close(); }
:
Java下載檔案