文件下载后台代码:
public static void download(HttpServletRequest request,HttpServletResponse response,String filePath){
ServletContext servletContext = request.getSession().getServletContext();
File file = new File( filePath);
//设置文件MIME类型
response.setContentType( servletContext.getMimeType( file.getName()));
//设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;fileName="+file .getName());
OutputStream out;
//读取目标文件,通过response将目标文件写到客户端
try {
InputStream in = new FileInputStream( file);
out = response.getOutputStream();
int b = 0;
while(( b= in.read())!= -1) {
out.write( b);
}
in.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
html代码:
<input type= "hidden" id ="download-url" value="<c:url value="/application/fileDownload.do"/>" />
<a class= "btn btn_item" id= "export-page" >导出页面 </a>
js代码:
function fileDownload() {
var $exportFile = $( '#export-page');
var downloadUrl = $( '#download-url').val();
var fileName = 'card_information.html';
var url = downloadUrl + "?fileName=" + fileName;
window.location. href = url;
}