下载的js:
/** * @param target_URL 下载地址 * @param onload 服务器返回结果的回调函数 * @param fileName 文件名 不传则从服务端获取 Content-disposition filename=* * @param save_URL 保存路径 先不写了 */ function downLoadFile(target_url,onloadFunction,filename,save_URL){ var req = new XMLHttpRequest(); req.open("POST", target_url, true); req.responseType = "blob"; req.onreadystatechange = function () { if (req.readyState === 4 && req.status === 200) { if(!filename){ filename = req.getResponseHeader("Content-disposition"); filename = filename.substring(filename.indexOf("filename=")+9,filename.length); filename = decodeURI(filename); } if (typeof window.chrome !== 'undefined') { // Chrome version var link = document.createElement('a'); link.href = window.URL.createObjectURL(req.response); link.download = filename; link.click(); } else if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE version var blob = new Blob([req.response], { type: 'application/force-download' }); window.navigator.msSaveBlob(blob, filename); } else { // Firefox version var file = new File([req.response], filename, { type: 'application/force-download' }); window.open(URL.createObjectURL(file)); } } }; req.onload = onloadFunction; req.ontimeout = function(e) { //下载超时 }; req.onerror = function(e) { //下载出错 }; req.send(); }
java主要代码:
File templetFile = new File(request.getSession().getServletContext().getRealPath("/")+"WEB-INF/teple/测试模板.xls"); downLoadExcel(response, new HSSFWorkbook(new FileInputStream(templetFile)),templetFile.getName()); private void downLoadExcel(HttpServletResponse response, Workbook workbook,String fileName){ OutputStream output = null; try { response.reset(); response.setHeader("Content-disposition", "attachment; filename="+ URLEncoder.encode(fileName,"utf-8")); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setCharacterEncoding("utf-8"); output = response.getOutputStream(); workbook.write(output); output.flush(); } catch (Exception e) { //异常处理 } finally { try {if(output!=null)output.close();} catch (IOException e) {} } }
js调用:
loading、loadingClose()为自定义遮罩
$("button[filter='downTemplet']").click(function(){ loading(); downLoadFile("resolveExcel",loadingClose()); });