SpringMVC如何把后臺文件打印到前臺
實現(xiàn)效果如下:
代碼為:
@RequestMapping(value = "/tools/printContract") public void cell(HttpServletResponse response,HttpServletRequest request,String outName) { //根據(jù)outName獲取到保存在服務器上的文件 String filePath = request.getSession().getServletContext().getRealPath(ImgUtil.TOOLS_PATH+ImgUtil.TOOLS_TXT)+'/'+outName+".txt"; try(OutputStream out = response.getOutputStream()) { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss"); String dateString = formatter.format(currentTime); //fileName是輸出的文件的名字(不支持中文),包括了后綴 String fileName = "EncryptFile_" + dateString + ".txt"; byte[] bytes = FileEcodeUtil.file2byte(filePath); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition","attachment;filename=" + fileName); response.setContentLength(bytes.length); out.write(bytes); out.flush(); } catch (IOException e) { //e.printStackTrace(); } } //上面用到的file2byte方法為: public static byte[] file2byte(String filePath) { byte[] buffer = null; File file = new File(filePath); try (FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream()) { byte[] b = new byte[1024]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } buffer = bos.toByteArray(); } catch (Exception e) { // e.printStackTrace(); } return buffer; }
需要注意:返回值的類型是void 而不是String,不能返回到某一個頁面,否則服務器會拋出IllegalStateException異常,雖然在頁面上表現(xiàn)不出來。
java.lang.IllegalStateException: Cannot create a session after the response has been committed
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java畢業(yè)設計實戰(zhàn)之在線蛋糕銷售商城的實現(xiàn)
這是一個使用了java+JSP+Springboot+maven+mysql+ThymeLeaf+FTP開發(fā)的在線蛋糕銷售商城,是一個畢業(yè)設計的實戰(zhàn)練習,具有線上蛋糕商城該有的所有功能,感興趣的朋友快來看看吧2022-01-01SpringBoot2基于重復創(chuàng)建bean的問題及解決
這篇文章主要介紹了SpringBoot2基于重復創(chuàng)建bean的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06SpringBoot2.4.2下使用Redis配置Lettuce的示例
這篇文章主要介紹了SpringBoot2.4.2下使用Redis配置Lettuce,Springboot2.4.2下默認使用的就是Lettuce而不是Jedis因此無需在依賴進行排除Jedis,本文給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2022-01-01spring?boot?mybatis日志輸出到控制臺的方法實踐
在開發(fā)過程中我們往往需要打印出SQL語句,這樣就方便我們監(jiān)控問題,本文主要介紹了spring?boot?mybatis日志輸出到控制臺的方法實踐,具有一定的參考價值,感興趣的可以了解一下2024-05-05Springboot使用POI進行excel文件的導出與下載方式
這篇文章主要介紹了Springboot使用POI進行excel文件的導出與下載方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08