解决方法:这里是下载excel文件有问题,下载的时候指定响应内容类型为excel
response.setContentType("application/vnd.ms-excel");
记录:
public void downloadLocal(HttpServletResponse response, String fileName) throws IOException {
// 拼接文件路径
String filePath = "file" + File.separator + fileName;
log.info("下载文件路径:" + filePath);
log.info("下载文件名称:" + fileName);
String newFilePath = JsoupUtils.clean(filePath);
ClassPathResource cpr = new ClassPathResource(newFilePath);
log.info("ClassPathResource:" + cpr);
// 设置输出的格式
response.reset();
//正常输出流
if(fileName.contains(".xls")){
response.setContentType("application/vnd.ms-excel");
}else{
// response.setContentType("application/octet-stream");
response.setContentType("bin");
}
response.setCharacterEncoding("utf-8");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
InputStream inStream = null;
OutputStream outputStream = null;
try{
inStream = cpr.getInputStream();
outputStream = response.getOutputStream();
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
while ((len = inStream.read(b)) > 0) {
outputStream.write(b, 0, len);
}
} catch (IOException e) {
log.error(e.getMessage());
}finally {
if (inStream!=null){
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
刚开始使用response.setContentType("bin")
本地在postman上跑是是没有问题的,原始服务器也没问题,同样的代码换服务器跑就有问题。查看日志,也没报错,但是返回状态却是500,保存excel打开是乱码。
首先,乱码打不开,要考虑输出格式的问题。bin
是什么类型?好像是和application/octet-stream
一样,网上对bin
介绍太少,下载文件如果知道文件的类型,还是输出相对应的文件类型,不要用bin这种,可能是文件类的输出类型,不然会出现一些莫名奇妙的问题