java實現word、pdf檔案下載功能
在SpringMVC的開發過程中,有時需要實現文件的下載功能。文件的下載功能涉及到了java IO流操作的基礎知識,下面本文詳細介紹java如何實現後臺文件下載功能。
首先根據文件在專案中的儲存路徑建立File物件,並獲取文件的名稱和字尾。判斷瀏覽器型別,防止中文檔名出現亂碼。
File file=new File(path); String fileName=file.getName(); String ext=fileName.substring(fileName.lastIndexOf(".")+1); String agent=(String)request.getHeader("USER-AGENT"); //判斷瀏覽器型別 try { if(agent!=null && agent.indexOf("Fireforx")!=-1) { fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); //UTF-8編碼,防止輸出檔名亂碼 } else { fileName=URLEncoder.encode(fileName,"UTF-8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace();
之後,初始化讀入位元組流和讀出位元組流,並設定響應response的輸出屬性。
BufferedInputStream bis=null; OutputStream os=null; response.reset(); response.setCharacterEncoding("utf-8"); if(ext=="docx") { response.setContentType("application/msword"); // word格式 }else if(ext=="pdf") { response.setContentType("application/pdf"); // word格式 } response.setHeader("Content-Disposition", "attachment; filename=" + fileName); 接著呼叫inputStream和outputStream的read、write函式進行IO流讀寫操作。最後在寫出操作完成後,一定要關閉輸出流。
try { bis=new BufferedInputStream(new FileInputStream(file)); byte[] b=new byte[bis.available()+1000]; int i=0; os = response.getOutputStream(); //直接下載匯出 while((i=bis.read(b))!=-1) { os.write(b, 0, i); } os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); }finally { if(os!=null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } 這樣就可以使用java完成word、pdf文件的下載功能。