【问题标题】:Error: ENOENT: no such file or directory,错误:ENOENT:没有这样的文件或目录,
【发布时间】:2019-04-20 20:13:59
【问题描述】:

当我尝试通过邮递员上传图像并保存在 public/upload_files 文件夹中时,它会显示此错误

节点-v v10.15.3

npm -v 6.9.0

“错误:ENOENT:没有这样的文件或目录”

这是我的代码

const express = require('express'); 

const router = express.Router();    
const multer = require('multer');

const storage = multer.diskStorage({    
  destination: function(req, file, cb) {
    cb(null,'./public/uploaded_files');    
  },    
  filename: function(req, file, cb) {       
    cb(null,new Date().toISOString() + file.originalname);    
  } 
});

const upload = multer({storage:storage});    

router.post('/', upload.single('file'), (req,res,next) => {    
  console.log(req.file);
});

module.exports = router;

我只是想将图像保存在以下文件夹 public/upload_files

【问题讨论】:

  • 我试过了不工作。
  • 你写的文件夹,存在吗?
  • 是的,它存在。它给了我这个错误 Error: ENOENT: no such file or directory, open 'D:\Event\public\uploaded_files\2019-04-20T20:34:21.195Z025.JPG'
  • `D:\Event\public\uploaded_files` 这个路径是否正确?
  • 也许尝试在你的路径中不使用句号.,就像这样'\public\uploaded_files'

标签: node.js express


【解决方案1】:

我对我的代码进行了一些更改,它工作正常。

我添加了这一行

cb(null,path.join(__dirname,'../upload'))

还有这个

cb(null,Date.now() + path.extname(file.originalname))

代码

var storage = multer.diskStorage({
    
destination: function(req, file, cb)
    
{
        
cb(null,path.join(__dirname,'../upload'))
 
},
    
filename: function(req, file, cb)
    
{
        
cb(null,Date.now() + path.extname(file.originalname))
    }
});

【讨论】:

  • 对我不起作用,所以我使用了相对路径
【解决方案2】:

使用

cb(null, Date.now() + file.originalname);  

而不是

cb(null, new Date().toISOString() + file.originalname); 

防止

"error": "ENOENT: no such file or directory

【讨论】:

    【解决方案3】:

    这可能是由于禁止的文件名或操作系统操作。您是否在不同的操作系统中运行该程序?例如:某些操作系统不允许文件名包含由 new Date().toISOString() 函数生成的某些特殊字符。 补充:我认为这段代码来自 Max 的 Node js 课程。

    【讨论】:

      【解决方案4】:
        const storage = multer.diskStorage({
              destination: function(req, file, cb) {
                  cb(null, './public/uploaded_files');
              },
              filename: function(req, file, cb) {
                   // cb(null, new Date().toISOString() + file.originalname) // this is wrong
                  cb(null, Date.now() + file.originalname);
              }
          });
      

      【讨论】:

      • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
      猜你喜欢
      • 2017-10-07
      • 1970-01-01
      • 2019-03-09
      • 2017-12-28
      • 2022-01-16
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      相关资源
      最近更新 更多