亲宝软件园·资讯

展开

Node.js调用fs.renameSync报错(Error: EXDEV, cross-device link not permitted)

__Daniel 人气:0

在写一个文件上传的功能时候,调用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(, {"Content-Type": "text/html"});
  response.write("received image:<br/>");
  response.write("<img src='/show' />");
  response.end();
 });
 }

加载全部内容

相关教程
猜你喜欢
用户评论