nodejs提示 cross-device link not permitted, rename 错误解决方法
nodejs 提示
Error: EXDEV: cross-device link not permitted, rename ‘C:\Users\ADMINI~1\AppData\Local\Temp\upload_a371dca60fbe7310b8d6d97cf3597238’ -> ‘E:\nodejs\case\two\img\test.png’
文件上传的功能时候,调用fs.renameSync方法错误
这个提示是垮区重命名文件出现的权限问题。
先从源文件拷贝到另外分区的目标文件,然后再unlink,就可以了。
form.parse(request, function(error, fields, files) {
console.log(“parsing done”);
fs.renameSync(files.upload.path, “/tmp/test.png”);
});
改成
form.parse(request, function(error, fields, files) {
console.log(“parsing done”);// fs.renameSync(files.upload.path, “/nodejs/case/two/img/test.png”);
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); });});
PS:node版本是0.10.69可以使用上面的方法,如果使用的是0.6以下的版本,可以使用util.pump
相应代码只需将上面的代码中readStream.on处改成:(注意引入util模块)
util.pump(readStream,writeStream, function() { fs.unlinkSync('files.upload.path'); });
参考地址:https://stackoverflow.com/questions/12196163/node-js-fs-rename-doesnt-work
https://stackoverflow.com/questions/4568689/how-do-i-move-file-a-to-a-different-partition-or-device-in-node-js
方法二:
这种就简洁很多了
添加一个 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();
});
}