Simple upload method using node.js+express.js:
使用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;
}
The method iterates each uploaded file, creates a new filename and writes it to a given location set in metadata.
该方法迭代每个上载的文件,创建新文件名并将其写入元数据中设置的给定位置。
console.log('finished');
is fired when writing is finished, however the client never receives a response. After 2 minutes the request is cancled, however the file was uploaded.
写入完成后会被触发,但客户端永远不会收到响应。 2分钟后,请求被预定,但文件已上传。
Any ideas why this method does not return any response?
1 个解决方案
#1
1
You're using readFile
, which is async, too, and works like this:
您正在使用readFile,它也是异步的,并且工作方式如下:
fs.readFile('/path/to/file',function(e,data)
{
if (e)
{
throw e;
}
console.log(data);//file contents as Buffer
});
I you could pass a reference to a function here, to take care of this, but IMO, it'd be way easier to simply use readFileSync
, which returns the Buffer directly, and can be passed to writeFile
without issues:
我可以在这里传递一个函数的引用来处理这个,但IMO,简单地使用readFileSync会更容易,它直接返回Buffer,并且可以毫无问题地传递给writeFile:
fs.writeFile(r.metadata.newPath, r.readFileSync, function(err)
{
if (err)
{
throw err;
}
console.log('Finished');
});
Check the docs for readFile
and writeFile
respectively
分别检查文档的readFile和writeFile
#1
1
You're using readFile
, which is async, too, and works like this:
您正在使用readFile,它也是异步的,并且工作方式如下:
fs.readFile('/path/to/file',function(e,data)
{
if (e)
{
throw e;
}
console.log(data);//file contents as Buffer
});
I you could pass a reference to a function here, to take care of this, but IMO, it'd be way easier to simply use readFileSync
, which returns the Buffer directly, and can be passed to writeFile
without issues:
我可以在这里传递一个函数的引用来处理这个,但IMO,简单地使用readFileSync会更容易,它直接返回Buffer,并且可以毫无问题地传递给writeFile:
fs.writeFile(r.metadata.newPath, r.readFileSync, function(err)
{
if (err)
{
throw err;
}
console.log('Finished');
});
Check the docs for readFile
and writeFile
respectively
分别检查文档的readFile和writeFile