文件的上傳下載一般在項目中還是非常實用的,此處專門整理一下文件的下載,至于文件的上傳實現將在后續中補上。文件的下載多用于模板文件的下載,這在項目中用的還是挺多的。今天用到了就整理出來了,以供搬運工們借鑒并使用,已驗證無誤。
(1) 前臺實現
前臺實現非常簡單,不像文件上傳那樣復雜,只要給出一個超鏈接,鏈接到后臺處理的方法,并且需要將文件名傳入Controller。
(2) 后臺處理
后臺的Controller就主要處理這樣幾個問題:
①根據文件名,找到模板文件
②設置響應的形式、文件頭、編碼
③通過流的形式讀取模板文件內容并將之寫入輸出流
④關閉輸入輸出流
(3) 下面我們根據前臺后臺的實現思路來具體看一下實現代碼:
①前臺:
<a href="${base}/downloadTemplate?fileName=abilityTemplate.xlsx">模板下載</a>
②后臺:
@RequestMapping(value = "/downloadTemplate",method = RequestMethod.GET)
public String downloadAbilityTemplate(String fileName,HttpServletRequest request,HttpServletResponse response){
response.setCharacterEncoding("utf-8");//設置編碼
response.setContentType("mult response.setHeader("Content-Disposition", "attachment;fileName="+ fileName); //設置響應頭 try { String filePath = Config.getValue("path"); //獲取配置文件中模板文件所在目錄 String path = request.getsession().getServletContext().getRealPath("/")+filePath; //獲取模板文件的相對目錄 InputStream inputStream = new FileInputStream(new File(path+ File.separator + fileName)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); }//邊讀模板文件邊寫入輸出流 os.close(); inputStream.close();//關流 } catch (FileNotFoundException e) { e.PRintStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; //注意此時return null } (4) 注意點: ①返回模型層應該是return null,否則出現如下錯誤: java+getOutputStream()hasalreadybeencalledforthisresponse ②模板文件的位置可以根據需要存放,只要在后臺能獲取到此文件的全路徑就行 放在class目錄下獲取是: //獲取classes所在路徑 String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); //獲取WebRoot目錄: String path = request.getSession().getServletContext().getRealPath("/")
|
新聞熱點
疑難解答