先看效果:
Controller代碼:
/** * 平台實現更新包下載 * * @param request * @param response * @return * @throws UnsupportedEncodingException */ @RequestMapping("/download") @RequiresPermissions("update:manage:download") public R downloadFile(HttpServletRequest request, HttpServletResponse response, String fileFullName) throws UnsupportedEncodingException { String rootPath = propertiesconfig.getUploadpacketPath();//這里是我在配置文件里面配置的根路徑,各位可以更換成自己的路徑之后再使用(例如:D:/test) String FullPath = rootPath + fileFullName;//將文件的統一儲存路徑和文件名拼接得到文件全路徑 File packetFile = new File(FullPath); String fileName = packetFile.getName(); //下載的文件名 File file = new File(FullPath); // 如果文件名存在,則進行下載 if (file.exists()) { // 配置文件下載 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); // 下載文件能正常顯示中文 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 實現文件下載 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("Download the song successfully!"); } catch (Exception e) { System.out.println("Download the song failed!"); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } else {//對應文件不存在 try { //設置響應的數據類型是html文本,並且告知瀏覽器,使用UTF-8 來編碼。 response.setContentType("text/html;charset=UTF-8"); //String這個類里面, getBytes()方法使用的碼表,是UTF-8, 跟tomcat的默認碼表沒關系。 tomcat iso-8859-1 String csn = Charset.defaultCharset().name(); System.out.println("默認的String里面的getBytes方法使用的碼表是: " + csn); //1. 指定瀏覽器看這份數據使用的碼表 response.setHeader("Content-Type", "text/html;charset=UTF-8"); OutputStream os = response.getOutputStream(); os.write("對應文件不存在".getBytes()); } catch (IOException e) { e.printStackTrace(); } // return R.error("-1","對應文件不存在"); } return null; }
前台代碼:
function downloadFile(path) { layer.confirm('確定要下載選中的記錄?', { btn : [ '確定', '取消' ] }, function(index) { window.open("/update/send/download?fileFullName="+path) layer.close(layer.index); }) }