Bootstrap

【前端-网页篇】JavaScript下载文件到本地的方法总结

方法一:

/*****************************************/
/*fileName : 要下载文件的文件名*/
/*content: 要下载文件的文件内容*/
/*****************************************/
function downloadFileHelper(fileName, content) {
	const aTag = document.createElement('a');
	const blob = new Blob([content]);
   
	aTag.download = fileName;
	aTag.style = "display: none";
	aTag.href = URL.createObjectURL(blob);
	document.body.appendChild(aTag);
	aTag.click();
   
	setTimeout(function () {
	  document.body.removeChild(aTag);
	  window.URL.revokeObjectURL(blob);
	}, 100);
  };

方法二:

var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/json;charset=utf-8,' + encodeURIComponent(content));
pom.setAttribute('download', filename);

if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}

方法三:

var filename = '文件名';
var blob = new Blob([arr], {type: "application/octet-stream"});
saveAs(blob, filename);

该方法需要引入FileSaver.js文件
FileSaver.js下载地址

;