2014-08-23
今天开始学习Node.js,在写一个文件上传的功能时候,调用fs.renameSync方法错误
出错代码所在如下:
function upload(response,request){
console.log("upload called");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
fs.renameSync(files.upload.path, "./tmp/test.jpg");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
大致分析后,预计是因为跨磁盘分区移动或操作文件会有权限问题。
下面提供两种解决办法:
方法一:
主要利用fs的createReadStream、createWriteSream和unlinkSync方法
具体代码如下:
function upload(response,request){
console.log("upload called");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
// fs.renameSync(files.upload.path, "./tmp/test.jpg");
var readStream=fs.createReadStream(files.upload.path);
var writeStream=fs.createWriteStream("./tmp/test.jpg");
readStream.pipe(writeStream);
readStream.on('end',function(){
fs.unlinkSync(files.upload.path);
});
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
PS:我用的node版本是0.10.69,如果使用的是0.6以下的版本,可以使用util.pump
相应代码只需将上面的代码中readStream.on处改成:(注意引入util模块)
util.pump(readStream,writeStream, function() {
fs.unlinkSync('files.upload.path');
});
方法二:
这种就简洁很多了
添加一个 form.uploadDir='tmp' 即可(写一个临时路径)
function upload(response,request){
console.log("upload called");
var form = new formidable.IncomingForm();
form.uploadDir='tmp';
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
fs.renameSync(files.upload.path, "./tmp/test.jpg");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
解决问题后,就可以很开心的继续我的Node学习了,感觉路还很长啊
PS:附上两个有关Node文件上传的帖子,个人觉得挺不错的,来源都是cnode