新手问题.关于express文件上传出现error:ENOENT, No such file or directory的Nodejs问题
新手问题.关于express文件上传出现error:ENOENT, No such file or directory的Nodejs问题
exports.submit = function(req, res, next){
var original_path = req.files.filesubmit.path;
var target_path = ‘./submitted/’;
console.log(path.existsSync(original_path));//-----------//TRUE!
fs.rename(original_path, target_path, function(err){
if (err) throw err;//------//error:ENOENT,No such file or directory
fs.unlink(tmp_path, function(){
// ir (err) throw err;
res.send(‘submitted’);
})
})
}
明明path.existsSync(original_path)是TRUE,
为何抛出error:ENOENT,No such file or directory
当然可以!让我们来分析一下这个问题,并提供一个解决方案。
问题分析
error: ENOENT, No such file or directory
这个错误通常表示指定的路径不存在。虽然你使用 path.existsSync(original_path)
检查了原始路径是否存在,但可能是因为目标路径(target_path
)没有正确地指定文件名,导致文件无法移动。
示例代码及解释
我们可以通过以下步骤来解决这个问题:
- 确保目标路径是一个完整的文件路径:这包括文件名。
- 处理文件名冲突:如果文件已经存在,可能会导致错误。
下面是修改后的代码示例:
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
const upload = multer({ dest: 'uploads/' }); // 设置临时存储位置
app.post('/upload', upload.single('filesubmit'), function(req, res, next) {
const originalPath = req.file.path;
const targetPath = path.join('./submitted/', req.file.originalname); // 确保目标路径包含文件名
console.log(path.existsSync(originalPath)); // 检查原始路径是否存在
fs.rename(originalPath, targetPath, function(err) {
if (err) {
console.error("Error moving file:", err);
return res.status(500).send('Failed to move file');
}
fs.unlink(originalPath, function(err) {
if (err) {
console.error("Error deleting temporary file:", err);
return res.status(500).send('Failed to delete temporary file');
}
res.send('File submitted successfully');
});
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
关键点解释
- Multer 中间件:我们使用 Multer 来处理文件上传。
multer({ dest: 'uploads/' })
设置了临时存储位置。 - 完整的目标路径:
targetPath
使用path.join()
方法生成一个完整的文件路径,包括文件名。 - 错误处理:在
fs.rename()
和fs.unlink()
中添加了错误处理逻辑,以确保在出现问题时能够及时反馈给客户端。
通过这些修改,你应该能够解决 ENOENT
错误,并成功将上传的文件移动到目标目录中。
fs的rename 不允许跨 分区移动文件~
没权限
这个问题应该如何解决啊?
为什么呢,我的Mac,不是说windows才有这个问题吗
target_path 这个很可能为false,所以报了error,要么是没有权限, 你在你的./路径下先建好这个文件夹,应该就能解决了
在你的代码中,path.existsSync(original_path)
返回 true
表明 original_path
所指向的文件确实存在。然而,在调用 fs.rename()
时抛出了 ENOENT
错误,这可能是因为目标路径 target_path
没有正确指定。
你需要确保 target_path
是一个完整的路径,并且该目录存在。此外,fs.rename()
方法需要提供完整的目标路径(包括文件名)。
以下是一个修复后的示例代码:
const fs = require('fs');
const path = require('path');
exports.submit = function(req, res, next) {
var original_path = req.files.filesubmit.path;
var target_path = path.join('./submitted', req.files.filesubmit.name);
console.log(fs.existsSync(original_path)); // TRUE
fs.rename(original_path, target_path, function(err) {
if (err) throw err;
fs.unlink(original_path, function() {
res.send('submitted');
});
});
// 确保目标目录存在
if (!fs.existsSync('./submitted')) {
fs.mkdirSync('./submitted');
}
};
在这个示例中,我们使用 path.join()
来生成目标路径,并确保目标目录 ./submitted
存在。这样可以避免 ENOENT
错误。