測試用的后端代碼
// 1.獲取下載目標(biāo)
String filename = "aa.txt";
System.out.println(filename);
// 2.找到下載目標(biāo)
String path = getServletContext().getRealPath("download/" + filename);
System.out.println("path:"+path);
File file = new File(path);
if (file.exists()) {
// 3.如果文件存在钝计,那么設(shè)置響應(yīng)的內(nèi)容為下載处窥,告訴瀏覽器將信息識別成下載
// 判斷一下瀏覽器
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("找不到文件");
}