SpringBoot下載Excel文件時,報錯文件損壞的解決方案
SpringBoot下載Excel文件文件損壞
我把模板文件放在了resources目錄下

maven插件打包項目的時候,默認會壓縮resources目錄下的文件。
服務器讀取的文件流來自于壓縮后的文件,而返回給瀏覽器時,瀏覽器把他當作正常的文件解析,自然不能得到正確的結果。
解決方案:
配置一下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,也會出現文件的中文名亂碼的情況。
想徹底解決亂碼問題,我們還需要在代碼中需要做一些處理。
下面貼一個工具類,看大概思路即可。
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項目中,下載文件出現異常:
SpringBoot下載文件,出現異常:Could not find acceptable representation

接口定義為:
public XResponse<Void> exportProject(@PathVariable("projectId") String projectId,
HttpServletResponse response) throws Exception
原因:在下載文件時,接口不能有返回值
將接口定義修改為:
public void exportProject(@PathVariable("projectId") String projectId,
HttpServletResponse response) throws Exception
此時下載就沒有異常信息了。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
搭建Springboot框架并添加JPA和Gradle組件的方法
這篇文章主要介紹了搭建Springboot框架并添加JPA和Gradle組件的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
IDEA的默認快捷鍵設置與Eclipse的常用快捷鍵的設置方法
這篇文章主要介紹了IDEA的默認快捷鍵設置與Eclipse的常用快捷鍵的設置方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
SpringBoot+SpringBatch+Quartz整合定時批量任務方式
這篇文章主要介紹了SpringBoot+SpringBatch+Quartz整合定時批量任務方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09

