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

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

SpringBoot下載Excel文件時(shí),報(bào)錯(cuò)文件損壞的解決方案

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

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

SpringBoot下載Excel文件時(shí),報(bào)錯(cuò)文件損壞的解決方案

maven插件打包項(xiàng)目的時(shí)候,默認(rèn)會(huì)壓縮resources目錄下的文件。

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

解決方案:

配置一下maven插件,打包的時(shí)候不要壓縮模板文件,排除拓展名為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,也會(huì)出現(xiàn)文件的中文名亂碼的情況。

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

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

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àng)目中,下載文件出現(xiàn)異常:

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

SpringBoot下載Excel文件時(shí),報(bào)錯(cuò)文件損壞的解決方案

接口定義為:

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

將接口定義修改為:

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

此時(shí)下載就沒有異常信息了。

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

標(biāo)簽: excel
主站蜘蛛池模板: 盐边县| 浦北县| 醴陵市| 苏州市| 独山县| 手游| 化德县| 民丰县| 思南县| 宣恩县| 鹿泉市| 镇安县| 通江县| 邳州市| 元谋县| 方城县| 泽州县| 扶沟县| 延长县| 拜泉县| 五指山市| 大田县| 水城县| 广宗县| 南靖县| 唐河县| 建宁县| 云霄县| 鸡东县| 长岭县| 农安县| 邳州市| 北京市| 山丹县| 华宁县| 湘乡市| 嘉荫县| 西充县| 莲花县| 渭南市| 肥城市|