由于用IO流下载.xlsx .docx 文件时报文件损坏的错误修复,找了半天原因,终于解决了,记录一下原因,以及解决方案 一.出现损坏的原因: 并不是每次都能读到1024个字节,所有用len作为每次读取数据的长度,否则会出现文件损坏的错误 二.解决方法(注意红的部分代码) 1.原本文件下载代码如下: public void Downloads(HttpServletResponse response , String url){ try { File file = new File(url); String str = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String name=str+".xlsx"; if(file.exists()){ //判断文件父目录是否存在 response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8")); response.setHeader("Pragma", URLEncoder.encode(name, "UTF-8")); byte[] buffer = new byte[1024]; FileInputStream fis = null; //文件输入流 BufferedInputStream bis = null; OutputStream os = null; //输出流 os = response.getOutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); while(bis.read(buffer) != -1){ os.write(buffer); } bis.close(); fis.close(); } }catch (Exception e){ e.printStackTrace(); logger.warn("sys:zydownload:Downloads--userId:"+ ShiroUtils.getUserId()+"===="+e.getMessage()); } } 注:这种写法会出现IO流下载.xlsx .docx 文件时报文件损坏的错误修复,改成下面的写法则可以解决
2.改进后的代码
public void Downloads(HttpServletResponse response , String url){
try {
File file = new File(url);
String str = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String name=str+".xlsx";
if(file.exists()){ //判断文件父目录是否存在
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));
response.setHeader("Pragma", URLEncoder.encode(name, "UTF-8"));
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int len = 0; while((len = bis.read(buffer)) >0){ os.write(buffer, 0, len); }
bis.close();
fis.close();
}
}catch (Exception e){
e.printStackTrace();
logger.warn("sys:zydownload:Downloads--userId:"+ ShiroUtils.getUserId()+"===="+e.getMessage());
}
}