本篇内容主要讲解“web导出文件核心代码实例”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“web导出文件核心代码实例”吧!
创新互联-专业网站定制、快速模板网站建设、高性价比东平网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式东平网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖东平地区。费用合理售后完善,10年实体公司更值得信赖。
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导出文件核心代码实例”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!