久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

SpringBoot下載Excel文件時,報錯文件損壞的解決方案

瀏覽:164日期:2022-06-15 16:17:51
SpringBoot下載Excel文件文件損壞

我把模板文件放在了resources目錄下

SpringBoot下載Excel文件時,報錯文件損壞的解決方案

maven插件打包項目的時候,默認(rèn)會壓縮resources目錄下的文件。

服務(wù)器讀取的文件流來自于壓縮后的文件,而返回給瀏覽器時,瀏覽器把他當(dāng)作正常的文件解析,自然不能得到正確的結(jié)果。

解決方案:

配置一下maven插件,打包的時候不要壓縮模板文件,排除拓展名為xlsx的文件。

<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><configuration> <encoding>UTF-8</encoding> <nonFilteredFileExtensions><nonFilteredFileExtension>xlsx</nonFilteredFileExtension> </nonFilteredFileExtensions></configuration> </plugin>

即使這里配置了utf-8,也會出現(xiàn)文件的中文名亂碼的情況。

想徹底解決亂碼問題,我們還需要在代碼中需要做一些處理。

下面貼一個工具類,看大概思路即可。

package com.zikoo.czjlk.utils; import com.zikoo.czjlk.exception.EmServerError;import com.zikoo.czjlk.exception.EmServerException; import javax.servlet.http.HttpServletResponse;import java.io.*;import java.net.URLEncoder; public class FileUtils { public static void download(HttpServletResponse response, String filePath, String fileName){ try { response.setHeader('content-type', 'application/octet-stream'); response.setContentType('application/octet-stream'); response.setHeader('Content-Disposition', 'attachment;filename=' + URLEncoder.encode(fileName,'UTF-8')); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); writeBytes(is, response.getOutputStream());}catch (Exception e) { throw new EmServerException(EmServerError.FILE_OPERATION_ERROR);} } private static void writeBytes(InputStream is, OutputStream os) {try { byte[] buf = new byte[1024]; int len = 0; while((len = is.read(buf))!=-1) {os.write(buf,0,len); }}catch (Exception e) { throw new EmServerException(EmServerError.FILE_OPERATION_ERROR);}finally { if(is != null) {try { is.close();} catch (IOException e) { e.printStackTrace();} } if(os != null) {try { os.close();} catch (IOException e) { e.printStackTrace();} }} }}在SpringBoot項目中,下載文件出現(xiàn)異常:

SpringBoot下載文件,出現(xiàn)異常:Could not find acceptable representation

SpringBoot下載Excel文件時,報錯文件損壞的解決方案

接口定義為:

public XResponse<Void> exportProject(@PathVariable('projectId') String projectId, HttpServletResponse response) throws Exception 原因:在下載文件時,接口不能有返回值

將接口定義修改為:

public void exportProject(@PathVariable('projectId') String projectId, HttpServletResponse response) throws Exception

此時下載就沒有異常信息了。

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: excel
主站蜘蛛池模板: 砀山县| 长寿区| 厦门市| 饶平县| 浦城县| 翁牛特旗| 安达市| 宁南县| 建水县| 永宁县| 孝感市| 阿图什市| 斗六市| 弥勒县| 饶平县| 阿荣旗| 浑源县| 巧家县| 德江县| 扶余县| 遂平县| 仙桃市| 南宁市| 栖霞市| 崇左市| 和静县| 溧阳市| 嘉鱼县| 莆田市| 蕲春县| 巴里| 尼勒克县| 谢通门县| 濮阳市| 通州区| 东莞市| 周至县| 景谷| 玉门市| 石景山区| 招远市|