我已成功将文件上传到临时目录,并希望将它们移动到目录 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');
});
});
});
但这会导致错误:
Error: ENOENT, rename 'tmp/5162-2fftn.jpg'] errno: 34, code: 'ENOENT', path: 'tmp/5162-2fftn.jpg'
顶部的图像是我的 SFTP 管理器连接到此应用程序的工作目录的屏幕截图,因此显然该目录确实存在!
我的错误是什么?
我是一名优秀的程序员,十分优秀!