java中使用springmvc實現下載文件


下載文件具體實現代碼:

public class TestDownload{   public HttpServletRequest request;   public HttpServletResponse response;   //下載文件
  public static void downLoadFile(){     String downloadFileName = "下載后文件名_TEST.xlsx"; FileInputStream inputStream = null; OutputStream outputStream = null; File file = null; try { file = new File(getFilePath(request)); if (!file.exists()) { log.info("日報文件不存在,請重新導出數據"); } else { inputStream = new FileInputStream(file); response.setContentType("application/txt;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;Filename=" + new String(downloadFileName.getBytes("GB2312"), "ISO8859-1"));// 設置下載后文件的名字、防止中文亂碼
 outputStream = response.getOutputStream(); byte[] bytes = new byte[1024]; int len = 0; while ((len = inputStream.read(bytes)) > 0) { outputStream.write(bytes, 0, len); } }       } catch (IOException e) {   log.error("文件下載異常:", e);   } finally {   try {    if (inputStream != null) {    inputStream.close();   }   if (outputStream != null) {    outputStream.close();   }   } catch (IOException e) {    log.error("下載日報中關閉流異常 :{} ", e);    }   }   } //獲取服務器文件路徑
  private String getFilePath(HttpServletRequest request) { String fileName = "服務器文件.xlsx"; String projectPath = request.getSession().getServletContext().getRealPath("/downloadfile/tset"); return projectPath + "/" + fileName; } }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM