【问题标题】:ENOENT: no such file or directory .?ENOENT:没有这样的文件或目录。?
【发布时间】:2018-07-03 06:34:36
【问题描述】:

这是发布数据和文件时出现的错误。 我已按照“academind”教程构建 Restful API 服务,我也一直在寻找此类错误的答案,但对我没有任何帮助。

我正在使用“multer”上传文件

文件夹中的“上传”文件夹可用,但它显示

ENOENT:没有这样的文件或目录,打开 'D:\project\uploads\2018-01-24T07:41:21.832Zcheck.jpg'"

app.js

const express = require("express");
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const productRoutes = require("./api/routes/products");

mongoose.connect('',
(err)=>{
    if(err){console.log(err)}
    else{console.log('DB Connected')}
})
mongoose.Promise = global.Promise;

app.use(morgan("dev"));
app.use('/uploads', express.static('uploads'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
    return res.status(200).json({});
  }
  next();
});

// Routes which should handle requests
app.use("/products", productRoutes);

app.use((req, res, next) => {
  const error = new Error("Not found");
  error.status = 404;
  next(error);
});

app.use((error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  });
});

module.exports = app;

product.js

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

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

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

router.post("/", checkAuth, upload.single('productImage'), (req, res, next) => {
  const product = new Product({
    _id: new mongoose.Types.ObjectId(),
    name: req.body.name,
    price: req.body.price,
    productImage: req.file.path 
  });
  product
    .save()
    .then(result => {
      console.log(result);
      res.status(201).json({
        message: "Created product successfully",
        createdProduct: {
            name: result.name,
            price: result.price,
            _id: result._id,
            request: {
                type: 'GET',
                url: "http://localhost:3000/products/" + result._id
            }
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

module.exports = router;

【问题讨论】:

  • 根据this page,文件名中不允许使用冒号(:)。尝试删除它(product.js 中的第 11 行)。

标签: node.js express multer


【解决方案1】:

在 product.js 中:

new Date().toISOString() 之后添加 replace() 以将 ":" 更改为可接受的字符。

Windows 操作系统不接受带有 ":"

的文件

Youtube 上的人正在使用 MAC OS

例如

new Date().toISOString().replace(/:/g, '-')

【讨论】:

  • 谢谢你。有同样的问题,这为我解决了它
  • 这个答案值得更多的支持。
【解决方案2】:

尝试以下方法:

  1. 要求将此作为常量 (const path = require('path');)
  2. 改变这一行

    cb(null, './uploads/');

有了这个:

cb(null, path.join(__dirname, '/uploads/'));

如我所见,您正在尝试获取不在服务器上的路径,而是在服务器机器上的路径。

更新

尝试同时更改此设置

app.use('/uploads', express.static('uploads'));

到这里:

app.use(express.static(__dirname));

为了暴露静态文件的__dirname。

【讨论】:

  • 我添加了 'cb(null, 'D:/project/uploads');'但还是一样
  • 不要使用 'D:/project/uploads',使用 __dirname 全局对象。 nodejs.org/docs/latest/api/modules.html#modules_dirname
  • 同样的错误,console.log(__dirname) 结果 D:\project
  • 错误一定是 express.static 无法为静态文件托管您的文件夹
  • 非常感谢。为我节省了许多小时的压力。添加 next(null, path.join(__dirname, '.././public/uploads/images/'));工作
【解决方案3】:

这对我有用。我将 './uploads/' 更改为 '__dirname' 以便它可以在您计算机上的任何位置找到正确的目录/文件名。

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

因为当您设置特定的文件夹名称/目录时,您将图像目录限制为仅或应该在该文件夹中。

【讨论】:

  • 谢谢。它正在工作。
【解决方案4】:

我正在做同样的课程,我也有同样的问题(我也使用 Windows 机器)。以下对我有用:

const hash = require('random-hash'); // you have to install this package:

const fileStorage = multer.diskStorage({
    destination: (req, file, callback) => { //this is storing the file in the images folder
        callback(null, path.join(__dirname, '/Images'));
    },

    filename: (req, file, callback) => { //this is just setting a unique filename
        let temp = file.originalname.split('.');
        const filename = temp[0] + '-' + hash.generateHash({length: 5}) + '.' + temp[1]
        callback(null, filename);
    }
});

这也会为文件名创建一个唯一的哈希

【讨论】:

  • 您也可以使用节点内置的加密库来生成哈希。因此,您不必添加另一个依赖项。 crypto.randomBytes(16).toString("hex") -> 该位将生成哈希
【解决方案5】:

我在 cmets 部分找到了这个,这里:https://www.youtube.com/watch?v=srPXMt1Q0nY&list=PL55RiY5tL51q4D-B63KBnygU6opNPFk_q&index=10

好的,如果有人在创建文件时遇到问题 阶段,这可能意味着您正在使用 Windows。现在,你不 需要感到气馁,把你的电脑扔进垃圾桶(我 实际上就像总是必须为我的 Windows 找到解决方法:)。

至少有一个解决方案,这是我找到的。我的问题 是因为 Windows 不接受文件没有被创建 带有冒号 (':') 的文件名。我的解决方案相当简单。后 我得到当前日期,我使用 replace() 和一个正则表达式来改变它 成破折号。中提琴。有效!

以防万一,这是一种方法: 文件名:函数(请求,文件,cb){ const now = new Date().toISOString(); const date = now.replace(/:/g, '-'); cb(null, date + file.originalname); }

希望它对在 Windows 中工作的人有所帮助。

【讨论】:

    【解决方案6】:

    所以答案在 youtube 上的教程 cmets 部分。 而不是:

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

    做:

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

    简单。

    【讨论】:

      【解决方案7】:

      使用 this = > cb(null, Date.now() + file.originalname); 而不是 cb(null, new Date().toISOString() + file.originalname); 来防止 "error": "ENOENT: no such file or directory

      【讨论】:

        【解决方案8】:

        一切都很好。问题出在这条线上 cb(null, new Date().toISOString() + file.originalname); 只需写cb(null,file.originalname); 它会起作用的。尝试以不同的方式使用文件名添加日期字符串。

        【讨论】:

          【解决方案9】:

          您应该更改文件名。因为 Windows 中不允许使用 ':'。

          例如:

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

          【讨论】:

            【解决方案10】:

            我在保存文件时遇到了同样的错误。 我在回调中提供的路径不存在,这就是我收到该错误的原因

            const fs = require('fs');
            const storage = multer.diskStorage({
              destination: function(req, file, cb) {
                fs.mkdir('./uploads/',(err)=>{
                   cb(null, './uploads/');
                });
              },
              filename: function(req, file, cb) {
                cb(null, new Date().toISOString() + file.originalname);
              }
            });
            

            使用文件系统我创建了相同的文件夹,如果文件夹存在,err 会获得价值,但这里没有什么可担心的,因为我们有那个文件夹。 这对我有用。希望这会有所帮助

            【讨论】:

            • 是的......我花了一个小时才弄清楚该文件夹应该已经存在,然后它才保存文件。
            【解决方案11】:

            我认为如果您使用 Windows 操作系统,您应该使用Date().i 的另一种方法编写代码:

            filename:(req,file,cb)=>{ cb(null,new Date().toDateString()+file.originalname) }
            

            【讨论】:

              【解决方案12】:

              我遇到了类似的错误,这就是我解决它的方法。使用替换方法后,我将 './uploads/images/' 更改为 'uploads/images'。在这种情况下,multer 自动创建了该文件夹。所以你有这样的东西

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

              对于 Windows 用户。

              【讨论】:

                【解决方案13】:

                在 app.js 文件附近创建文件夹 uploads

                对于这一行

                app.use('/uploads', express.static('uploads'));
                

                【讨论】:

                  【解决方案14】:

                  如果找不到文件夹,那么您可以创建一个

                  destination: function(req, file, cb) {
                      fs.mkdir('./uploads/',(err)=>{
                         cb(null, './uploads/');
                      });
                    },
                  

                  【讨论】:

                    【解决方案15】:

                    在这里,许多其他人都非常接近,我确信某些答案对某些人有用,但是我发现here 对我有用(为此苦苦挣扎)现在 2 周)。

                        const storage = multer.diskStorage({
                    
                      destination: function (req, file, cb) {
                        cb(null, path.resolve(__dirname, './test'))
                      },
                    
                      filename: function (req, file, cb) {
                        cb(null, file.originalname)
                      }
                    })
                    

                    【讨论】:

                      【解决方案16】:

                      您无权访问此服务器上的 /uploads/。

                      尝试以下方法:

                      sudo chmod -R 777 /uploads
                      

                      【讨论】:

                        【解决方案17】:

                        注意:为了去除所有特殊字符,我们可以使用替换功能

                        const cleanVariable = mixSpecialCharters.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
                        

                        【讨论】:

                          【解决方案18】:
                          const storage = multer.diskStorage({
                            destination: function(req, file, cb) {
                              -cb(null, './uploads/');
                              +cb(null, 'upload/');
                            },
                            filename: function(req, file, cb) {
                              cb(null, new Date().toISOString() + file.originalname);
                            }
                          });
                          

                          【讨论】:

                          • 添加更多细节
                          【解决方案19】:

                          在 product.js 中只需将 cb(null, new Date().toISOString()+ file.originalname) 替换为 cb(null, Date.now() + "-" + file.originalname);

                          【讨论】:

                            【解决方案20】:

                            只是改变

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

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

                            【讨论】:

                              猜你喜欢
                              • 1970-01-01
                              • 2014-01-12
                              • 1970-01-01
                              • 2023-03-31
                              • 2013-07-28
                              • 2019-02-03
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              相关资源
                              最近更新 更多