【问题标题】:express fileupload : no such file or directoryexpress fileupload : 没有这样的文件或目录
【发布时间】:2019-08-29 21:05:43
【问题描述】:

我正在使用 express-file 包。我是这样使用的:

const upload = require('express-fileupload');
app.use(upload({
    createParentPath: true
}));

这就是我的存储方式:

await req.files.main_image.mv('./public/images/movies/'+main_image);

我已经创建了 public/images 目录。我在 public/images 目录中没有电影目录。

什么时候可以工作:如果我已经创建了 /public/images/movies 目录,它就可以工作

当它不起作用时:如果我没有创建 /public/images/movies 目录,但有 /public/images 目录。然后它说:

ENOENT:没有这样的文件或目录,打开 'C:\Users\glagh\Desktop\Work\MoviesAdviser\public\images\movies\1554741546720-8485.11521.brussels.the-hotel-brussels.amenity.restaurant-AD3WAP2L-13000-853x480.jpeg

如何自动创建 /movies 目录并将图像放在那里?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    Express-fileupload 使用以下code 创建您传递给.mv 函数的目录路径:

    const checkAndMakeDir = function(fileUploadOptions, filePath){
      //Check upload options were set.
      if (!fileUploadOptions) return false;
      if (!fileUploadOptions.createParentPath) return false;
      //Check whether folder for the file exists.
      if (!filePath) return false;
      const parentPath = path.dirname(filePath);
      //Create folder if it is not exists.
      if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath); 
      return true;
    };
    

    问题是fs.mkdirSync() 没有使用您指定的父目录创建完整路径(请注意,您将在 shell 上使用mkdir -p 来创建整个文件夹结构)-> 结帐How to create full path with node's fs.mkdirSync? 了解更多信息信息。

    您可以做的是使用fs-extra 之类的模块并使用它的function ensureDir 在调用.mv() 函数之前创建相应的父目录(如果它们尚不存在)。 或者,如果您的节点版本 >= 10,请使用本机 {rescursive:true} 选项,您可以将其传递给 fs.mkdirSync

    【讨论】:

    • @Nika Kurashvili:有这方面的消息吗?
    猜你喜欢
    • 2020-10-29
    • 2020-06-03
    • 1970-01-01
    • 2016-11-29
    • 2021-06-24
    • 2023-03-19
    • 2015-02-20
    • 1970-01-01
    相关资源
    最近更新 更多