15

I saw in documentation of multer, that if folder doesn't exist, the multer will not create folder. How can i create a folder if not exist?

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))
      })
    }
  })
}

2 Answers 2

38

i had change to:

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))
      })
    }
  })
}
Sign up to request clarification or add additional context in comments.

2 Comments

You should use mkdirSync only if the directoyy doesn't exists (you could existsSync function wich returns a boolean).
exist is deprecated method, i can do this, with code above. Thanks
1

I have done it in this way, and it works fine for me. so you can try. hopefully it will work for you. good luck

#########controller##########

// 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
}
router
xxxRouterWeb.post('/addXXXAudio', auth,
        xxxController.upload, xxxController.addBalayAudio)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.