下載部分的代碼
前台:
<a th:href="'/FileDownload?fileDirType=meeting_minute_docx&fileName='+${meetingMsg.meetingId}+'.docx&fileId='+${meetingMsg.meetingId}+'.docx'" >紀要文件.doc</a>
后台:
@ResponseBody @RequestMapping("/FileDownload") public String downLoad(HttpServletResponse response,@RequestParam( "fileDirType") String fileDirType,@RequestParam( "fileName") String fileName,@RequestParam( value = "fileId",required = false) String fileId ) throws UnsupportedEncodingException { System.out.println("fileDirType:"+fileDirType); File fileDir=UploadUtils.getDownLoadDirFile(fileDirType); String filePath = fileDir.getAbsolutePath(); File file = new File(filePath + "/" + fileId); System.out.println(file.getAbsolutePath()); if(file.exists()){ //判斷文件父目錄是否存在 response.setContentType("application/plain;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName,"UTF-8")); byte[] buffer = new byte[1024]; FileInputStream fis = null; //文件輸入流 BufferedInputStream bis = null; OutputStream os ; //輸出流 try { os = response.getOutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); int i = bis.read(buffer); while(i != -1){ os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("----------file download---" + fileName); try { bis.close(); fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "下載成功"; } return "下載失敗"; }
下載docx文件打開時有一個問題:(點擊是后發現可以正常顯示,但發現下載后的docx比原文件大了)
下載txt文件發現多了一個“下”字,也就是說把return中的內容也加進來了。
把downLoad方法改為void后下載可正常顯示,目前還不清楚原因。