/**PageBeginHtml Block Begin **/ /***自定义返回顶部小火箭***/ /*生成博客目录的JS 开始*/ /*生成博客目录的JS 结束*/

javascript实现客户端兼容各浏览器 导出文件




javascript实现客户端兼容各浏览器创建csv并下载的方法


  1 $("#radarDLBut").click(function(){
  2 var data = [displayData["radar_chart"]["r_label"],displayData["radar_chart"]["r_default"]];
  3 var csvContent = "data:text/csv;charset=utf-8,\ufeff";
  4 if (window.navigator.msSaveOrOpenBlob) {
  5   csvContent = "\ufeff";
  6 }
  7 data.forEach(function(infoArray, index){
  8   dataString = infoArray.join(",");
  9   csvContent += index < data.length ? dataString+ "\n" : dataString;
 10 });
 11 if (window.navigator.msSaveOrOpenBlob) {
 12   // if browser is IE
 13   var blob = new Blob([decodeURIComponent(encodeURI(csvContent))],{
 14  type: "text/csv;charset=utf-8;"
 15   });
 16   navigator.msSaveBlob(blob, 'subject.csv');
 17 }else{
 18   var encodedUri = encodeURI(csvContent);
 19   var link = document.createElement("a");
 20   link.setAttribute("href", encodedUri);
 21   link.setAttribute("download", "subject.csv");
 22   document.body.appendChild(link);
 23   link.click();
 24 }
 25 });




js实现保存Txt文件到本地-兼容各浏览器

先上代码:支持IE8+,Edge,Firefox,Chrome。

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 
  4 <head>
  5    <meta charset="UTF-8">
  6    <title>Save Test</title>
  7   <script>
  8 	function save(filename,data){
  9 		var ua = window.navigator.userAgent.toLowerCase();
 10 		//alert(ua);
 11 		var version = (ua.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
 12 
 13 		if(ua.indexOf("edge") > -1 || (ua.indexOf("msie") == -1 && version =='11.0') || (ua.indexOf("msie") > -1 && version == '10.0' )) {
 14 			window.navigator.msSaveOrOpenBlob(new Blob([ data ]), filename);
 15 			return;
 16 		}
 17 	   // for IE9-
 18 	   if(ua.indexOf("msie") > -1 && (version == '9.0' || version == '8.0')){
 19 			var frame = document.createElement("iframe");
 20 			if (frame) {
 21 				document.body.appendChild(frame);
 22 				frame.setAttribute("style", "display:none");
 23 				frame.contentWindow.document.open("txt/html", "replace");
 24 
 25 				frame.contentWindow.document.write(data);
 26 				frame.contentWindow.document.close();
 27 				frame.focus();
 28 				frame.contentWindow.document.execCommand("SaveAs", true,
 29 						filename);
 30 				document.body.removeChild(frame);
 31 			}
 32 		}else if(ua.indexOf('firefox')>-1 || ua.indexOf('chrome')>-1){
 33 			var blob = new Blob([data]);
 34 			var link = document.getElementsByTagName('a')[0];
 35 			link.download = filename;
 36 			var url = URL.createObjectURL(blob);
 37 			link.href = url;
 38 			//URL.revokeObjectURL(url);
 39 		}
 40 	}
 41 
 42 
 43     window.onload = function(){
 44 		var data = 'hello world!';
 45 		save('file.txt',data);
 46 	}
 47   </script>
 48 </head>
 49 
 50 <body>
 51   <a>Save</a>
 52 </body>
 53 
 54 </html>
 55 








posted @ 2021-06-07 16:36  一品堂.技术学习笔记  阅读(148)  评论(0编辑  收藏  举报