1.可直接寫:location.href = "後臺請求地址"
2.用XMLHttpRequest形式(ajax axios fetch):javascript
axios({ url: url, params: parameter, method:'get' , responseType: 'blob' }).then(data=>{ if (!data) { alert("文件下載失敗") return } if (typeof window.navigator.msSaveBlob !== 'undefined') { //處理IE window.navigator.msSaveBlob(new Blob([data]), fileName+'.xls') }else{ let url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', fileName+'.xls') document.body.appendChild(link) link.click() document.body.removeChild(link); //下載完成移除元素 window.URL.revokeObjectURL(url); //釋放掉blob對象 } })
//從服務器上下載文件核心代碼 response.setContentType("application/x-msdownload;charset=utf-8"); String fileName="中文文件名.xls"; String userAgent = request.getHeader("user-agent").toLowerCase(); if (userAgent.contains("msie") || userAgent.contains("like gecko") ) { fileName = URLEncoder.encode(fileName, "UTF-8"); }else { fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); } response.setHeader("Content-disposition", "attachment; filename="+ fileName); InputStream inputStream = null; OutputStream outputStream=null; try { String imgurl = "服務器上的文件實際地址"; inputStream = new BufferedInputStream(new FileInputStream(imgurl)); outputStream = response.getOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } response.flushBuffer(); } catch (Exception e) { logger.info("--經過流的方式獲取文件異常--"+e.getMessage()); }finally{ if(inputStream!=null){ inputStream.close(); } if(outputStream!=null){ outputStream.close(); } }
//導出excel //此處省略 生成workbook的代碼 String fileName = "登記發證統計.xls"; String userAgent = req.getHeader("user-agent").toLowerCase(); if (userAgent.contains("msie") || userAgent.contains("like gecko") ) { fileName = URLEncoder.encode(fileName, "UTF-8"); }else { fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); } // 設置強制下載不打開 resp.setContentType("application/force-download"); resp.setHeader("Content-disposition", "attachment; filename="+ fileName); OutputStream out = resp.getOutputStream(); workbook.write(out); resp.flushBuffer();