java 文件下载 【学习记录】
工具类
public static Boolean downloadExcelFile(HttpServletResponse response, String fileName) {
OutputStream output;
File file = new File(fileName);
if (file.exists()) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInputStream);
byte[] b = new byte[bufferedInputStream.available()];
bufferedInputStream.read(b);
output = response.getOutputStream();
response.setHeader("Content-disposition","attachment; filename=" + DateUtil.getCurrentDate("yyyyMMddHHmmss") +new String("模板文件".getBytes("UTF-8"), "ISO8859-1")+ ".xls");
response.setContentType("application/msexcel");
output.write(b);
output.flush();
output.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}else {
return false;
}
}
注意的地方:
文件下载的请求 不能使用 ajax 发送请求 ,否则不会弹出下载框,文件内容会 被全部响应到如图
可以使用 发送请求
location.href=""