我正在成功地将文件上传到临时目录,并希望将它们移到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管理器连接到这个应用程序的工作目录的屏幕截图,所以这个目录显然是存在的!
我犯了什么错??
发布于 2016-06-09 21:33:49
为了解决这个问题,我自己花了几个小时。请看这里澄清一下,https://github.com/nodejs/node-v0.x-archive/issues/2703
这里的线程实际上指向了正确的方向,Move File in ExpressJS/NodeJS
是的,fs.rename不会在两个不同的磁盘/分区之间移动文件。这是正确的行为。fs.rename提供了在linux中重命名(2)的相同功能。
https://stackoverflow.com/questions/23986625
复制相似问题