java实现文件的下载
jsp 前台页面
//输入调用后台接口路径
<a href="../../sjModel">下载模板</a>
/**
* 数据模板
* LhT
* @throws IOException
* */
@RequestMapping(value = "sjModel")
public String sjModel(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
InputStream in = null;
OutputStream out = null;
String userAgent = request.getHeader("USER-AGENT");
try {
response.reset();
response.setContentType("application/x-msdownload;charset=UTF-8");
String file = "";
// 判断浏览器类别,对文件名编码不同
if (userAgent.indexOf("MSIE") > -1) {
// IE浏览器
file = Encodes.urlEncode("数据导入模板.xls");
} else {
// 其他浏览器
file = new String("数据导入模板.xls".getBytes("utf-8"), "iso-8859-1");
}
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + file + "\"");
String path = request.getSession().getServletContext().getRealPath("/static/数据导入模板.xls");// 获取配置文件地址
in = new FileInputStream(new File(path));
out = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.flush();
} catch (IOException ex) {
System.out.println(ex.getMessage());
} finally {
out.close();
in.close();
}
return null;
}