javascript实现生成并下载txt文件
方法一:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
} else {
pom.click();
}
}
调用方式:
download("data.txt","hello world");
方法二:
function download(filename,content,contentType) {
if (!contentType) contentType = 'application/octet-stream';
var a = document.createElement('a');
var blob = new Blob([content], { 'type': contentType });
a.href = window.URL.createObjectURL(blob);
a.download = filename;
a.click();
}
调用方式:
download("data.txt,"hello world");
在浏览器中可以设置默认保存地址,以及下载前询问每个文件的保存位置
方法三:
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
调用方法
download("data.txt","hello world");
打赏作者
微信
支付宝