js實現保存文件到本地-兼容各瀏覽器

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

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <title>Save Test</title>
  <script>  	
	function save(filename,data){
		var ua = window.navigator.userAgent.toLowerCase();
		//alert(ua);
		var version = (ua.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
	
		if(ua.indexOf("edge") > -1 || (ua.indexOf("msie") == -1 && version =='11.0') || (ua.indexOf("msie") > -1 && version == '10.0' )) {				
			window.navigator.msSaveOrOpenBlob(new Blob([ data ]), filename);
			return;
		} 	
	   // for IE9-
	   if(ua.indexOf("msie") > -1 && (version == '9.0' || version == '8.0')){
			var frame = document.createElement("iframe");
			if (frame) {
				document.body.appendChild(frame);
				frame.setAttribute("style", "display:none");
				frame.contentWindow.document.open("txt/html", "replace");
				
				frame.contentWindow.document.write(data);
				frame.contentWindow.document.close();
				frame.focus();
				frame.contentWindow.document.execCommand("SaveAs", true,
						filename);
				document.body.removeChild(frame);
			}
		}else if(ua.indexOf('firefox')>-1 || ua.indexOf('chrome')>-1){
			var blob = new Blob([data]);		
			var link = document.getElementsByTagName('a')[0];
			link.download = filename;
			var url = URL.createObjectURL(blob);
			link.href = url;
			//URL.revokeObjectURL(url);
		}
	}
	
	
    window.onload = function(){
		var data = 'hello world!';
		save('file.txt',data);
	}
  </script>
</head>

<body>
  <a>Save</a>
</body>

</html>

保存文件到本地用到的知識:

1. Blob對象

Blob = Binary Large Object的縮寫,直譯爲二進制大對象

1.1 創建Blob對象

var blob= new Blob(Array,options);

1.2 生成Blob鏈接

Blob URL是blob協議deURL,它的格式如下:
blob:http://xxx
在絕大部分場景下,我們可以像使用Http協議的URL一樣使用Blob URL。常見得場景有: 作爲文件得下載地址和作爲圖片資源地址。

URL.createObjectURL(blob); 如果傳入的參數是blob對象的話,則可以生成一個blob鏈接。
URL.revokeObjectURL() 靜態方法用來釋放一個之前通過調用 URL.createObjectURL() 創建的已經存在的 URL 對象。當你結束使用某個 URL 對象時,應該通過調用這個方法來讓瀏覽器知道不再需要保持這個文件的引用了。

1.3 msSaveBlob 和 msSaveOrOpenBlob 方法(IE10+)

IE10 以上的版本提供 msSaveBlob 和 msSaveOrOpenBlob 方法允許用戶在客戶端上保存文件,方法如同從 Internet 下載文件,這是此類文件保存到“下載”文件夾的原因。
msSaveBlob 和 msSaveOrOpenBlob 之間的區別就在於前者僅爲用戶提供“保存”按鈕,而後者不但提供“保存”按鈕,還提供“打開”按鈕。

2. iframe(IE9-)

iframe 元素會創建包含另外一個文檔的內聯框架(即行內框架)。
參考:
深入淺出iframe
Web前端之iframe詳解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章