Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

javascript - 如何在内存中创建文件供用户下载,而不是通过服务器下载?(How to create a file in memory for user to download, but not through server?)

Is there any way I can create a text file on the client side and prompt the user to download it, without any interaction with the server?

(有什么方法可以在客户端上创建文本文件并提示用户下载文本文件,而无需与服务器进行任何交互?)

I know I can't write directly to their machine (security and all), but can I create and prompt them to save it?

(我知道我不能直接写给他们的机器(安全性和全部),但是我可以创建并提示他们保存吗?)

  ask by Joseph Silber translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...