您好,登錄后才能下訂單哦!
本篇內容主要講解“web導出文件核心代碼實例”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“web導出文件核心代碼實例”吧!
1.可直接寫:location.href = "后臺請求地址"
2.用XMLHttpRequest形式(ajax axios fetch):
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();
生成workbook的示例
到此,相信大家對“web導出文件核心代碼實例”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。