使用node.js+express.js的简单上传方法:
upload: function(req, res, next){
//go over each uploaded file
async.each(req.files.upload, function(file, cb) {
async.auto({
//create new path and new unique filename
metadata: function(cb){
//some code...
cb(null, {uuid:uuid, newFileName:newFileName, newPath:newPath});
},
//read file
readFile: function(cb, r){
fs.readFile(file.path, cb);
},
//write file to new destination
writeFile: ['readFile', 'metadata', function(cb,r){
fs.writeFile(r.metadata.newPath, r.readFile, function(){
console.log('finished');
});
}]
}, function(err, res){
cb(err, res);
});
}, function(err){
res.json({success:true});
});
return;
}该方法迭代每个上传的文件,创建一个新的文件名,并将其写入元数据中的给定位置集。
console.log('finished');在完成写入时触发,但是客户端永远不会收到响应。2分钟后,请求可以打开,但是文件被上传了。
知道为什么这个方法不返回任何响应吗?
发布于 2013-09-17 11:22:54
您使用的是readFile,它也是异步的,其工作方式如下:
fs.readFile('/path/to/file',function(e,data)
{
if (e)
{
throw e;
}
console.log(data);//file contents as Buffer
});我可以在这里传递一个对函数的引用,以处理这个问题,但海事组织,简单地使用readFileSync就更容易了,它直接返回缓冲区,可以直接传递给writeFile,而不存在任何问题:
fs.writeFile(r.metadata.newPath, r.readFileSync, function(err)
{
if (err)
{
throw err;
}
console.log('Finished');
});分别检查readFile和writeFile的文档
https://stackoverflow.com/questions/18848106
复制相似问题