配置部分,請參考 java--文件上傳
html
1.controller層代碼
java
/** * 測試文件下載 * * **/ @RequestMapping(value = "/download/{fileName}", method = RequestMethod.GET) public ResultObject download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) { System.out.println("fileName:" + fileName); ResultObject ro = customerCommentService.down(fileName,request,response); return ro; }
2.service層代碼
瀏覽器
/** * 測試文件下載 * * **/ public ResultObject down(String fileName, HttpServletRequest request, HttpServletResponse response);
3.實現層代碼app
/** * 測試文件下載 * * **/ public ResultObject down(String fileName, HttpServletRequest request, HttpServletResponse response){ ResultObject ro = new ResultObject(); //設置響應內容類型 response.setContentType("text/html;charset=utf-8"); //以下也是一種響應類型 //response.setContentType("multipart/form-data"); //設置字符編碼 try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //輸入流 java.io.BufferedInputStream bis = null; //輸出流 java.io.BufferedOutputStream bos = null; //得到下載文件路徑 String ctxPath=request.getSession().getServletContext().getRealPath("/")+"Upload\\"; //測試文件 //fileName = "cc.txt"; //下載路徑 String downLoadPath = ctxPath + fileName; System.out.println("下載文件路徑:"+downLoadPath); try{ //獲取文件長度 long fileLength = new File(downLoadPath).length(); //設置文件輸出類型 response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); //從地址得到文件輸入流 //這個FileInputStream後面是否是應該寫成FileInputStream(new File(downLoadPath)) bis = new BufferedInputStream(new FileInputStream(downLoadPath)); //響應輸入流,輸出 bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; //從輸入流讀入到buff,從buff寫入輸出流 while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } //下載成功 }catch(Exception e) { e.printStackTrace(); //下載失敗 }finally { if (bis != null) { try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (bos != null) { try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return ro; }
4.在火狐瀏覽器輸入測試
192.168.2.67:8080/pets/download/cc
5.出現以下截圖編碼
自此,結束。code