思路:先创建文件存在项目一个地方,在配置response信息,再循环取出流中的数据,最后删除存的文件
注意:在前台请求的时候,只能是form表单请求,或者用window.open的方式,最后我采用了window.open的方式
核心代码:
InputStream inStream = new FileInputStream(file);
response.setContentType("application/ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+setFileDownloadHeader(request, realFileName));
// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
inStream.close();
response.getOutputStream().close();
public static String setFileDownloadHeader(HttpServletRequest request, String fileName)throws UnsupportedEncodingException {
final String agent = request.getHeader("USER-AGENT");
String filename = fileName;
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
filename = new String(fileName.getBytes(), "ISO8859-1");
} else if (agent.contains("Chrome")) {
// google浏览器
filename = URLEncoder.encode(filename, "utf-8");
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}