springboot中Excel文件下載踩坑大全
調(diào)用接口下載spring boot工程的resources目錄下的excel模板文件,非常常見的一個文件下載功能,但是卻容易遇到很多坑,下面總結(jié)記錄下。
問題一:下載的文件名稱出現(xiàn)中文亂碼的問題解決方案:
response.setHeader('Content-Disposition','attachment;filename=' + new String('下載模板'.getBytes('UTF-8'), 'ISO8859-1'));
說明:這是網(wǎng)上最常見的解決方案,經(jīng)過這樣的修改后,在瀏覽器上調(diào)用get請求下載的文件確實(shí)沒有出現(xiàn)文件名中文亂碼了。但是在swagger里面測試接口,下載的問題還是會出現(xiàn)中文亂碼。
問題二:在swagger中測試下載接口,點(diǎn)擊下載的文件,發(fā)現(xiàn)文件名是亂碼的問題這里我項(xiàng)目中使用的是springdoc-openapi-ui 1.5.9,基于的是openapi3.0的協(xié)議。整體使用方式和界面和swagger類似。
swagger中下載的文件,點(diǎn)擊開發(fā)后,文件名亂碼問題:
解決方案:
response.setHeader('Content-Disposition', 'attachment;fileName=' + URLEncoder.encode('線索導(dǎo)入模板.xlsx','utf8'));
說明:通過URLEncoder.encode函數(shù)對文件名稱處理后,無論是在瀏覽器調(diào)用GET請求下載文件,還是Swagger中調(diào)用下載接口,都不會出現(xiàn)文件名亂碼問題。
問題三:下載的excel文件打開時總是提示部分內(nèi)容有問題,嘗試恢復(fù)。
解決辦法:給response的Header設(shè)置大?。?/p>
/加上設(shè)置大小 下載下來的excel文件才不會在打開前提示修復(fù)response.addHeader('Content-Length',String.valueOf(file.length()));問題四:開發(fā)環(huán)境下載成功,打成jar包發(fā)布到服務(wù)器上部署就出現(xiàn)下載失敗問題
原因:Resource下的文件是存在于jar這個文件里面,在磁盤上是沒有真實(shí)路徑存在的,它其實(shí)是位于jar內(nèi)部的一個路徑。所以通過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、下載方法實(shí)現(xiàn)
/** * 下載線索模板 * @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);//加上設(shè)置大小 下載下來的excel文件才不會在打開前提示修復(fù)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
到此這篇關(guān)于springboot中Excel文件下載踩坑大全的文章就介紹到這了,更多相關(guān)springboot Excel文件下載內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章: