SpringBoot下载Excel文件时,报错文件损坏的解决方案
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 jlk.utils;
import ption.EmServerError;
import ption.EmServerException;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.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=" + de(fileName,"UTF-8"));
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
writeBytes(is, OutputStream());
}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
此时下载就没有异常信息了。
压缩文件损坏以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。