springboot中Excel文件下載踩坑大全
調用接口下載spring boot工程的resources目錄下的excel模板文件,非常常見的一個文件下載功能,但是卻容易遇到很多坑,下面總結記錄下。
問題一:下載的文件名稱出現中文亂碼的問題解決方案:
response.setHeader('Content-Disposition','attachment;filename=' + new String('下載模板'.getBytes('UTF-8'), 'ISO8859-1'));
說明:這是網上最常見的解決方案,經過這樣的修改后,在瀏覽器上調用get請求下載的文件確實沒有出現文件名中文亂碼了。但是在swagger里面測試接口,下載的問題還是會出現中文亂碼。
問題二:在swagger中測試下載接口,點擊下載的文件,發現文件名是亂碼的問題這里我項目中使用的是springdoc-openapi-ui 1.5.9,基于的是openapi3.0的協議。整體使用方式和界面和swagger類似。
swagger中下載的文件,點擊開發后,文件名亂碼問題:
解決方案:
response.setHeader('Content-Disposition', 'attachment;fileName=' + URLEncoder.encode('線索導入模板.xlsx','utf8'));
說明:通過URLEncoder.encode函數對文件名稱處理后,無論是在瀏覽器調用GET請求下載文件,還是Swagger中調用下載接口,都不會出現文件名亂碼問題。
問題三:下載的excel文件打開時總是提示部分內容有問題,嘗試恢復。
解決辦法:給response的Header設置大小:
/加上設置大小 下載下來的excel文件才不會在打開前提示修復response.addHeader('Content-Length',String.valueOf(file.length()));問題四:開發環境下載成功,打成jar包發布到服務器上部署就出現下載失敗問題
原因:Resource下的文件是存在于jar這個文件里面,在磁盤上是沒有真實路徑存在的,它其實是位于jar內部的一個路徑。所以通過ResourceUtils.getFile或者this.getClass().getResource('')方法無法正確獲取文件。
解決:通過ClassPathResource讀取文件流
ClassPathResource classPathResource = new ClassPathResource('template/template.xlsx');完整代碼
1、控制層代碼
@Operation(summary = '下載模版',description = '下載模版')@GetMapping('/download')public void download(HttpServletResponse response){ templateService.download(response);}
2、下載方法實現
/** * 下載線索模板 * @param response */public void download(HttpServletResponse response) { InputStream inputStream = null; BufferedInputStream bis = null; OutputStream outputStream = null; try {ClassPathResource classPathResource = new ClassPathResource('template/template.xlsx');inputStream = classPathResource.getInputStream();response.setContentType('application/octet-stream');response.setHeader('content-type', 'application/octet-stream');//待下載文件名String fileName = URLEncoder.encode('模板.xlsx','utf8');response.setHeader('Content-Disposition', 'attachment;fileName=' + fileName);//加上設置大小 下載下來的excel文件才不會在打開前提示修復response.addHeader('Content-Length',String.valueOf(classPathResource.getFile().length()));byte[] buff = new byte[1024];outputStream = response.getOutputStream();bis = new BufferedInputStream(inputStream);int read = bis.read(buff);while (read != -1) { outputStream.write(buff, 0, buff.length); outputStream.flush(); read = bis.read(buff);} } catch ( IOException e ) {log.error('文件下載失敗,e'); } finally {IOUtils.closeQuietly(outputStream);IOUtils.closeQuietly(inputStream);IOUtils.closeQuietly(bis); }}
參考:https://blog.csdn.net/Hi_Boy_/article/details/107198371
到此這篇關于springboot中Excel文件下載踩坑大全的文章就介紹到這了,更多相關springboot Excel文件下載內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: