js:
下载按钮触发的事件:
$("#download_log").click(function(e) {
//进行下载(后台需要调用c的动态库去下载文件,所以需要判断。调用成功才去真正的下载)
$.post($("#path").val()+"/log/toDownLoadLogs",{ },function(data) {
if(data.s=='false'){
$.messager.alert("消息提示", "网关端日志文件下载失败!", "info");
}else{
//文件已下载到项目,进行下载
downloadFileByForm(data.fileName);
}
},'json')
})
//文件下载(ajax回调函数进行调用)
function downloadFileByForm(fileName) {
var url = $("#path").val()+"/log/toLoadLogFile";
var form = $("<form></form>").attr("action", url).attr("method", "post");
form.append($("<input></input>").attr("type", "hidden").attr("name", "fileName").attr("value", fileName));
form.appendTo('body').submit().remove();
}
controller:
//下载文件,Ajax请求的,去调用c动态库下载文件,成功后才去调用真正的下载接口。
@RequestMapping("/log/toDownLoadLogs")
public void toDownLoadLogs(HttpServletRequest request, HttpServletResponse response,String gatewayType,String ip,String port,String time) throws NumberFormatException, IllegalAccessException, NativeException, IOException {
if("0".equals(gatewayType)) {
//下载软网关日志
String[] split = time.split("-");
String downLoadFile = loadDllUtils.DownLoadFile("SGW"+split[0]+split[1]+split[2]+".log", ip, Short.parseShort("8001"));
System.out.println(downLoadFile);
if(!"1".equals(downLoadFile)) {
//文件下载失败
response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.write("{\"s\":\"false\"}");
writer.flush();
writer.close();
}else {
//返回文件信息
String fileName="SGW"+split[0]+split[1]+split[2]+".log";
response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.write("{\"s\":\"success\",\"gatewayType\":\"0\",\"fileName\":\""+fileName+"\"}");
writer.flush();
writer.close();
}
}else {
//下载硬网关日志
}
}
//下载文件 真正的下载
@RequestMapping("/log/toLoadLogFile")
public void toLoadLogFile(HttpServletRequest request, HttpServletResponse response,String gatewayType,String fileName) throws IOException {
/*response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);*/
response.setHeader("Content-Disposition",
"attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
String property = request.getSession().getServletContext().getRealPath("/fileName");
InputStream in = new FileInputStream(property);
ServletOutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
in.close();
out.close();
}