如何在瀏覽器實現文件下載,保存數據?


html部分:

<button type="button">點我下載</button>

js部分:

                   document.querySelector('button').onclick = function(){
				var records = "這里是要下載的內容";
				downloadFn(records,'下載.txt')
			}
			
			function downloadFn (content,filename){
				var blob;
				var eleLink = document.createElement('a');
				if('download' in  eleLink){
					eleLink.download = filename;
					eleLink.style.display = 'none';
					blob = new Blob([content]);
					eleLink.href = window.URL.createObjectURL(blob);
					document.body.appendChild(eleLink);
					eleLink.click();
					document.body.removeChild(eleLink)
				}else{
					//瀏覽器兼容
					blob = new Blob([content]);
					window.navigator.msSaveOrOpenBlob(blob,filename)
				}
			}

  如果是json格式,可以去進行一下格式化,以便在文本查看。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM