原文地址 : http://blog.csdn.net/u013291076/article/details/53556985
在写一个文件上传的功能时候,调用fs.renameSync方法错误
出错 代码所在如下:
1 function upload(response,request){
2 console.log("upload called");
3 var form = new formidable.IncomingForm();
4 console.log("about to parse");
5 form.parse(request, function(error, fields, files) {
6 console.log("parsing done");
7 fs.renameSync(files.upload.path, "./tmp/test.jpg");
8 response.writeHead(200, {"Content-Type": "text/html"});
9 response.write("received image:<br/>");
10 response.write("![](/show)");
11 response.end();
12 });
13 }
大致分析后,预计是因为 跨磁盘分区移动 或操作文件会有权限问题。
下面提供两种解决办法:
方法一:
主要利用fs的createReadStream、createWriteSream和unlinkSync方法
具体代码如下:
1 function upload(response,request){
2 console.log("upload called");
3 var form = new formidable.IncomingForm();
4 console.log("about to parse");
5 form.parse(request, function(error, fields, files) {
6 console.log("parsing done");
7 // fs.renameSync(files.upload.path, "./tmp/test.jpg");
8 var readStream=fs.createReadStream(files.upload.path);
9 var writeStream=fs.createWriteStream("./tmp/test.jpg");
10 readStream.pipe(writeStream);
11 readStream.on('end',function(){
12 fs.unlinkSync(files.upload.path);
13 });
14 response.writeHead(200, {"Content-Type": "text/html"});
15 response.write("received image:<br/>");
16 response.write("![](/show)");
17 response.end();
18 });
19 }
方法二:
这种就简洁很多了
添加一个 form.uploadDir='tmp' 即可(写一个临时路径)
1 function upload(response,request){
2 console.log("upload called");
3 var form = new formidable.IncomingForm();
4 form.uploadDir='tmp';
5
6 console.log("about to parse");
7 form.parse(request, function(error, fields, files) {
8 console.log("parsing done");
9 fs.renameSync(files.upload.path, "./tmp/test.jpg");
10 response.writeHead(200, {"Content-Type": "text/html"});
11 response.write("received image:<br/>");
12 response.write("![](/show)");
13 response.end();
14 });
15 }
16