【发布时间】:2014-07-22 02:29:55
【问题描述】:
我已成功将文件上传到临时目录,并希望将它们移动到目录profile_pictures。好像是这么简单的事情,我居然在这里卡了一个小时!
使用 Express 和 fs 的非常简单的代码:
app.post('/upload', function (req, res, next) {
console.log("User uploading profile picture...");
var tmp_path = req.files.profile_picture.path; // get the temporary location of the file
var ext = path.extname(req.files.profile_picture.name); // get the extension of the file with the path module
var target_path = '/profile_pictures/' + req.body.username + ext; // set where the file should actually exists - in this case it is in the "images" directory
fs.rename(tmp_path, target_path, function (err) { // move the file from the temporary location to the intended location
if (err) throw err;
fs.unlink(tmp_path, function (err) { // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.profile_picture.size + ' bytes');
});
});
});
但这会导致错误:
错误:ENOENT,重命名“tmp/5162-2fftn.jpg”] errno:34,代码:“ENOENT”,路径:“tmp/5162-2fftn.jpg”
上面的图片是我的 SFTP 管理器连接到这个应用程序的工作目录的屏幕截图,所以很明显该目录确实存在!
我的错误是什么?
【问题讨论】:
-
尽管有错误,您仍在继续,如果有
err,您不应该继续。此外,您的第二个回调未声明err参数,因此您不知道取消链接的错误是什么。 -
@Esailija 哦,我明白了。那么错误在
fs.rename。我会修复错误处理 -
你试过使用绝对路径吗?相对路径可能会认为根与您预期的不同
-
我没试过,没有。我正在使用 linux 服务器; linux 路径的根部分是什么样的..?就像在 Windows 中一样,它是
C:\ -
与操作系统无关,我的意思是当您将
./tmp之类的相对路径传递给fs.rename时,它会自行计算出绝对路径,这可能不是正确的路径。试试像"/var/www/node/tmp/file.jpg"这样的绝对路径。
标签: javascript node.js express fs