前言
最近在学习node.js,今天在写一个文件上传的功能,调用fs.rename上传文件时程序报了错。
具体如下:
Error: EXDEV: cross-device link not permitted, rename 'C:\Users\Simple_Y\AppData\Local\Temp\12920-ww17q9.vtx0mb1emi.jpg' ->
'E:\杨宇杰_备份2\光盘资源\Node.js实战\code\8\photo_app\public\photos\281295.jpg'
at Error (native)
大致意思应该是说不能跨盘符上传文件,涉及到权限问题。
问题代码
下面贴出我的代码(部分):
exports.submit = function (dir) {
return function(req, res, next){
var img = req.files.photo.image;
var name = req.body.photo.name || img.name;
var path = join(dir, img.name);
//fs.rename(img.path, path, function(err){
//if (err) return next(err);
解决办法
经过百度,终于找到了解决办法:
将上面的注释掉的两行代码换成下面的代码
fs.readFile(img.path, function (err, data) {
if (err) throw err;
console.log('File read!');
// Write the file
fs.writeFile(path, data, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
console.log('File written!');
});
// Delete the file
fs.unlink(img.path, function (err) {
if (err) throw err;
console.log('File deleted!');
});
结尾
至此,运行程序,问题完美解决。
感谢万能的百度!