使用node.js动态创建文件并使其可供下载 [英] Dynamically creating a file with node.js and make it available for download
问题描述
我正在Node.js中构建文本编辑器,用户可以在其中在文本区域中创建文件.完成文件编辑后,他可以按下导出"按钮,该按钮触发一个Jquery函数,该函数读取textarea并将文本发布到node.js服务器上.服务器应读取该信息并返回文件.我想避免在服务器上创建文件并提供服务,而是希望通过流动态创建文件.我已经尝试使用以下方法,但是没有用:
I am building a text editor in Node.js where a user create a file in a textarea. When he is done editing the file, he can push an "export" button that triggers a Jquery function that reads the textarea and post the text on the node.js server. The server should read the information and return a file. I would like to avoid creating a file on the server and servicing it, I'd rather create a file on the fly with streams. I have tried using the following and but that didn't work:
exports.exportfile = function(req,res){
var Stream = require('stream')
var stream = new Stream();
res.setHeader('Content-disposition', 'attachment; filename=try.txt');
res.setHeader('Content-type', 'text/plain');
stream.pipe = function(dest) {
dest.write('Hello Dolly')
}
stream.pipe(res)
}
有人对如何实现这一目标有任何见识吗?
Does anybody have any insight on how to achieve this?
推荐答案
我在服务器上对其进行了测试,并且可以正常工作.它来自GET调用,但我不明白为什么它不适用于POST.
I tested this on my server and it worked. It was from a GET call but I don't see why it wouldn't work with a POST.
res.setHeader('Content-disposition', 'attachment; filename=theDocument.txt');
res.setHeader('Content-type', 'text/plain');
res.charset = 'UTF-8';
res.write("Hello, world");
res.end();
这篇关于使用node.js动态创建文件并使其可供下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!