【问题标题】:multer create folder if not exist如果不存在,请创建文件夹
【发布时间】:2020-01-08 13:01:44
【问题描述】:

我在 multer 的文档中看到,如果文件夹不存在,multer 将不会创建文件夹。如果文件夹不存在,如何创建?

import multer from 'multer'
import crypto from 'crypto'
import { extname, resolve } from 'path'
import slug from 'slug'

export default {
  storage: multer.diskStorage({
    destination: resolve(__dirname, '..', '..', 'uploads', 'gallery'),
    filename: (req, file, cb) => {
      const { id, description } = req.body

      crypto.randomBytes(8, (err, res) => {
        if (err) return cb(err)

        return cb(null, id + '/' + res.toString('hex') + '/' + slug(description, { lower: true }) + extname(file.originalname))
        // return cb(null, res.toString('hex') + extname(file.originalname))
      })
    }
  })
}

【问题讨论】:

    标签: node.js multer


    【解决方案1】:

    我已更改为:

    import multer from 'multer'
    import crypto from 'crypto'
    import { extname } from 'path'
    import slug from 'slug'
    import fs from 'fs'
    
    export default {
      storage: multer.diskStorage({
        destination: (req, file, cb) => {
          const { id } = req.body
          const path = `./uploads/gallery/${id}`
          fs.mkdirSync(path, { recursive: true })
          return cb(null, path)
        },
        filename: (req, file, cb) => {
          const { description } = req.body
    
          crypto.randomBytes(3, (err, res) => {
            if (err) return cb(err)
    
            return cb(null, slug(description, { lower: true }) + '_' + res.toString('hex') + extname(file.originalname))
          })
        }
      })
    }
    

    【讨论】:

    • 只有当directoyy不存在时才应该使用mkdirSync(你可以existsSync函数返回一个布尔值)。
    • exist 是不推荐使用的方法,我可以做到这一点,上面的代码。谢谢
    【解决方案2】:

    我就是这样做的,对我来说效果很好。所以你可以试试。希望它对你有用。祝你好运

    #########控制器##########

    // image Upload
    const multer = require('multer')
    const path = require('path')
    const fs = require("fs");
    
    const storage = multer.diskStorage({
        destination: (req, file, cb) => {
    
            balayAudPath = 'media/content/agriInput/balay/audio'
    
            fs.mkdirSync(balayAudPath, { recursive: true })
            cb(null, balayAudPath)
        },
        filename: (req, file, cb) => {
            cb(null, Date.now() + path.extname(file.originalname))
        }
    })
    
    const upload = multer({
            storage: storage
        }).fields([
            { name: 'contentAudio', maxCount: 1 }
        ])
        //.single('imageFile');
        // .array('images', 3)  //| for upload multiple files
    
    module.exports = {
        upload
    }
    
    路由器
    xxxRouterWeb.post('/addXXXAudio', auth,
            xxxController.upload, xxxController.addBalayAudio)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-24
      • 2011-01-19
      • 2018-09-05
      • 2018-02-10
      • 2017-06-28
      • 2013-11-05
      • 2020-07-12
      相关资源
      最近更新 更多