SpringMVC 下載java
@RequestMapping(value = "/downDataPacket") public void downDataPacket(@RequestParam(value="sessionId", required=true) Long sessionId,HttpServletResponse response){ log.debug("SessionAuditController--downDataPacket---sessionId:"+sessionId); String fileName="download-single.txt"; if(null!=fileName&&(!"".equals(fileName))){ log.debug("------start down file!!!-----"); response.reset();// 不加這一句的話會出現下載錯誤 response.setHeader("Content-disposition", "p_w_upload; filename="+fileName);// 設定輸出文件頭 response.setContentType("text/x-plain");// 定義輸出類型 ServletOutputStream out = null; FileInputStream fis = null; BufferedInputStream inputBufStream = null; BufferedOutputStream outputBufStream = null; try { out = response.getOutputStream(); String path = "D:\\down\\download-single.txt"; fis = new java.io.FileInputStream(path); inputBufStream = new BufferedInputStream(fis); outputBufStream = new BufferedOutputStream(out); byte[] cache = new byte[2048]; int offset = 0; while ((offset = inputBufStream.read(cache, 0, cache.length)) > 0) { outputBufStream.write(cache, 0, offset); } outputBufStream.flush(); outputBufStream.close(); inputBufStream.close(); fis.close(); out.close(); } catch (Exception e) { e.printStackTrace(); this.error("下載異常!"); log.debug("------start down false!!!-----"); }finally{ try { if (out != null) out.close(); if (outputBufStream != null) outputBufStream.close(); if (inputBufStream != null) inputBufStream.close(); if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } this.info("下載成功!"); log.debug("------start down success!!!-----"); } }