导出功能的实现,主要记录总结导出过程中出现的一些问题。
public R templateDown(HttpServletResponse response) {
String fileName = "template.xlsx";
// 清空response
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload");
try {
//解决乱码
String exportName = "导入模板.xlsx";
String fileNameCode = URLEncoder.encode(exportName,"UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileNameCode);
//获取文件路径
String fileUrl = emergencyPath;
//获取项目在服务器上的真实路径
fileUrl = fileUrl + File.separator + fileName;
File file = new File(fileUrl);
if (!file.exists()) {
// response.sendError(500, "File not found!");
return R.fail("模板文件不存在");
}
long fileLength = file.length();
response.setHeader("Content-Length", String.valueOf(fileLength));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
return R.success("导出成功");
}
// 清空response
response.reset();
String fileNameCode = URLEncoder.encode(exportName,"UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileNameCode);
fileName = URLEncoder.encode(fileName,"utf-8");
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("utf-8"),"ISO8859-1"));