本篇内容主要讲解“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。