nodejs文件读写服务器,如何读取nodejs中的文件从Web客户端发送的服务器

formidable是一个使用表单非常方便的库。

下面的代码是一个功能齐全的示例节点应用程序,我从强大的github中取得并稍作修改。它只是显示上看到一个表单,并处理从POST形式上传,阅读文件和呼应其内容:

var formidable = require('formidable'),

http = require('http'),

util = require('util'),

fs = require('fs');

http.createServer(function(req, res) {

if (req.url == '/upload' && req.method.toLowerCase() == 'post') {

// parse a file upload

var form = new formidable.IncomingForm();

form.parse(req, function(err, fields, files) {

res.writeHead(200, {'content-type': 'text/plain'});

// The next function call, and the require of 'fs' above, are the only

// changes I made from the sample code on the formidable github

//

// This simply reads the file from the tempfile path and echoes back

// the contents to the response.

fs.readFile(files.upload.path, function (err, data) {

res.end(data);

});

});

return;

}

// show a file upload form

res.writeHead(200, {'content-type': 'text/html'});

res.end(

'

'+

'
'+

'
'+

''+

'

'

);

}).listen(8080);

这显然是一个很简单的例子,但对于大型文件强大是伟大的太。它使您可以访问解析后的表单数据的读取流。这使您可以在数据上传时处理数据,或者直接将数据输入到另一个数据流中。

// As opposed to above, where the form is parsed fully into files and fields,

// this is how you might handle form data yourself, while it's being parsed

form.onPart = function(part) {

part.addListener('data', function(data) {

// do something with data

});

}

form.parse();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值