Simple solution for HTML5 ready browsers...(适用于HTML5的浏览器的简单解决方案...)
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); }
form * { display: block; margin: 10px; }
<form onsubmit="download(this['name'].value, this['text'].value)"> <input type="text" name="name" value="test.txt"> <textarea name="text"></textarea> <input type="submit" value="Download"> </form>
Usage(用法)
download('test.txt', 'Hello world!');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…