不支持HTML5的浏览器实现
function downFile() {
var content = "hello world";
var blob = new Blob([content], { type: 'application/octet-stream' });
var fileName = "a.txt";
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
}
支持HTML5的浏览器实现(HTML5版)
<a download="a.txt" href="data:application/octet-stream,HELLO WORLD">Click me</a>
支持HTML5的浏览器实现(JavaScript版)
function download() {
var filename = 'a.txt';
var content = 'hello world';
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;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();
}
}