测试用的后端代码
// 1.获取下载目标
String filename = "aa.txt";
System.out.println(filename);
// 2.找到下载目标
String path = getServletContext().getRealPath("download/" + filename);
System.out.println("path:"+path);
File file = new File(path);
if (file.exists()) {
// 3.如果文件存在,那么设置响应的内容为下载,告诉浏览器将信息识别成下载
// 判断一下浏览器
String agent = request.getHeader("User-Agent");
if (agent.contains("Firefox")) {// 火狐
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {// ie和谷歌
filename = URLEncoder.encode(filename, "utf-8");
}
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
// 4.获取文件流
FileInputStream fis = new FileInputStream(file);
OutputStream os = response.getOutputStream();
// 5.返回给浏览器
int len = 0;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();// flush一下,确保一下
os.close();
fis.close();
} else {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("找不到文件");
}