1,899   JS NodeJS

学习node.js,做上传图片时报错

D:\code\testnode>node index.js
httpServer is started
start time : 2015年12月06日 星期日 15:07:21
request is coming, pathName is /upload
Route a request for /upload
Request handler for upload
end time : 2015年12月06日 星期日 15:07:21
get image
fs.js:681
  return binding.rename(pathModule._makeLong(oldPath),
                 ^

Error: EXDEV: cross-device link not permitted, rename 'C:\Users\LUCKYB~1\AppData\Local\Temp\upload_29140a3f0beef9745cc76a7dd37233d4' -> 'D:\test.jpg'
    at Error (native)
    at Object.fs.renameSync (fs.js:681:18)
    at D:\code\testnode\requestHandler.js:41:6
    at IncomingForm. (D:\code\testnode\node_modules\formidable\lib\incoming_form.js:105:9)
    at emitNone (events.js:67:13)
    at IncomingForm.emit (events.js:166:7)
    at IncomingForm._maybeEnd (D:\code\testnode\node_modules\formidable\lib\incoming_form.js:553:8)
    at D:\code\testnode\node_modules\formidable\lib\incoming_form.js:230:12
    at WriteStream. (D:\code\testnode\node_modules\formidable\lib\file.js:70:5)
    at WriteStream.g (events.js:260:16)

经核查是磁盘跨区的权限问题,解决方法:
1,图片缓存路径和保存路径设置为同一块磁盘

function upload(response,request){

	console.log("Request handler for upload");

	var form = new formidable.IncomingForm();
        //图片缓存路径
	form.uploadDir='D:/tmp/';
	form.parse(request,function(error,fields,files){
		console.log("get image");
                //图片保存路径
		fs.renameSync(files.upload.path,"D:/test.jpg");
		response.writeHead(200, {"Content-Type": "text/html"});
		response.write("")
		response.end();
	});


}

2,复制图片缓存到保存图片的路径,再unlink

var util = require('util');

function upload(response,request){

	console.log("Request handler for upload");

	var form = new formidable.IncomingForm();
        //图片缓存路径
	// form.uploadDir='D:/tmp/';
	form.parse(request,function(error,fields,files){
		console.log("get image");
                //图片保存路径
                var readStream = fs.createReadStream(files.upload.path)
                var writeStream = fs.createWriteStream("D:/test.jpg);
     
                util.pump(readStream, writeStream, function() {
                  fs.unlinkSync(files.upload.path);
                });
                
		//fs.renameSync(files.upload.path,"D:/test.jpg");
		response.writeHead(200, {"Content-Type": "text/html"});
		response.write("")
		response.end();
	});


}




Leave a Reply

Your email address will not be published. Required fields are marked *