1. 前端页面
<a id="downloadBtn" href="http://127.0.0.1:8080/admin/bigCustomer/download.html" class="btn btn-primary btn-sm pull-right" >模板下载</a>
2.后端代码
private final static String TEMPLATE_EXCEL_URL = "download";
private final static String TEMPLATE_EXCEL_NAME = "人员管理之模块.xlsx";
/**
*
* 下载Excel导入模板
*
* @param request
* @param response
* @return 下载Excel导入模板
* @throws Exception
*/
public Object downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
OutputStream os = null;
try {
String filepath = request.getServletContext().getRealPath(TEMPLATE_EXCEL_URL);
String path = filepath + File.separator + TEMPLATE_EXCEL_NAME;
File file = new File(path);// path是根据日志路径和文件名拼接出来的
String filename = file.getName();// 获取日志文件名称
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
response.setContentType("application/octet-stream");
os = new BufferedOutputStream(response.getOutputStream());
os.write(buffer);// 输出文件
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
3. 模板位置