【问题标题】:how to create year/month/day structure when uploading files with nodejs multer?使用nodejs multer上传文件时如何创建年/月/日结构?
【发布时间】:2021-06-27 14:09:10
【问题描述】:

我想使用 multer 将文件上传到带有年/月/日的文件夹结构中。 比如上传/2021/06/27/文件名。我该怎么做?

//configuring multer storage for images
const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'upload/');
    },
    filename: (req, file, cb) => {
        cb(null, new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname);
    }
});

【问题讨论】:

    标签: node.js express file-upload multer


    【解决方案1】:

    您可以使用fs 库函数创建自定义函数,

    • 初始化 fs 库
    const fs = require("fs");
    
    • 根据输入参数当前日期创建返回日期路径的方法
    • 例如:
      • 输入:new Date()
      • 返回:“2021/6/27”
    function getDatePath(date) {
        return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
    }
    
    • 如果目录不存在递归创建,可以用try-catch块处理
    function getDirPath(dirPath) {
        try {
            if (!fs.existsSync(dirPath)) fs.promises.mkdir(dirPath, { recursive: true });
            return dirPath;
        } catch (error) {
            console.log(error.message);
        }
    }
    
    • 在目的地使用上述方法
    //configuring multer storage for images
    const fileStorage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, getDirPath('upload/' + getDatePath(new Date())));
        },
        filename: (req, file, cb) => {
            cb(null, new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2017-03-29
      • 1970-01-01
      • 2017-10-09
      • 2021-07-25
      • 1970-01-01
      相关资源
      最近更新 更多