從Spring 控制器下載PDF 檔案
背景:
背景:從Web 應用程式高效能下載檔案是一個常見的要求。本文解決了從 Spring 控制器下載產生的 PDF 檔案的挑戰。
產生 PDF 文件:要產生 PDF 文件,請考慮使用 Freemarker 模板和PDF生成框架如iText。這允許根據使用者輸入或其他資料動態產生 PDF 內容。
透過控制器下載檔案:要透過Spring 控制器啟用檔案下載:
@RequestMapping(value = "/download/pdf/{fileName}", method = RequestMethod.GET) public void downloadPdf(@PathVariable("fileName") String fileName, HttpServletResponse response) { ... }
以InputStream的形式取得PDF資料。這可能涉及調用 PDF 生成邏輯或從存儲位置獲取文件。
response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
IOUtils.copy(inputStream, response.getOutputStream());
刷新回應以將 PDF 檔案傳送到客戶端。這將啟動下載過程。
範例程式碼:@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET) public void getFile( @PathVariable("file_name") String fileName, HttpServletResponse response) { try { // get your file as InputStream InputStream is = ...; // copy it to response's OutputStream IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { log.info("Error writing file to output stream. Filename was '{}'", fileName, ex); throw new RuntimeException("IOError writing file to output stream"); } }
以上是如何有效率地從 Spring 控制器下載產生的 PDF 檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!