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
此時下載就沒有異常信息了。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
