檔案下載模板
阿新 • • 發佈:2021-10-21
檔案下載模板
public void downloadFile(HttpServletResponse response){ InputStream inputStream = null; OutputStream outputStream = null; try{ // 讀到流中 inputStream = ; //自定義檔名稱 String fileName = ; String fileName = new String(filename.getBytes("GBK"),"ISO8859-1");莫聽穿林打葉聲,何妨吟嘯且徐行!!!// 設定輸出的格式 response.reset(); response.addHeader("Content-Disposition", String.format("attachment;filename=\"%s\"",fileName)); response.setContentType("application/octet-stream"); outputStream = new BufferOutputStream(response.getOutputStream); // 迴圈取出流中的資料 byte[] chuf = new byte[1024]; int len; while ((len = inStream.read(chuf)) > 0){ outputStream.write(chuf, 0, len); } outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try{if (inputStream != null) inputStream .close(); } catch (IOException e) { e.printStackTrace(); } try{ if (outputStream != null) outputStream .close(); } catch (IOException e) { e.printStackTrace(); } } }