1

I want to create a different folder for every fileType using the multer module. However, The fileType constant variable seems to be undefined in the multer disk storage, whereas it is correctly caught when I access in the .post middleware function:

app.post('/storeOnHDD', upload.single('file'), (req, res) => {
    console.log(req.body) // outputs the file and the file type
    if (!req.file) {
        return res.status(400).send('No file uploaded');
    }

    res.status(200).send({
        message: 'File uploaded successfully',
        file: req.file,
    });
})

Client side app

const formData = new FormData()

        console.log(file)
        formData.append('file', file)
        formData.append('fileType', 'video')

        axios.post('http://localhost:5000/storeOnHDD', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        })
            .then(res => {
                console.log(res.data)
            })
            .catch((err) => {
                console.log(err)
            })

Server side app

const express = require('express')
const cors = require('cors')
const multer = require('multer')
const fs = require('fs')

const app = express();
app.use(cors())
app.use(express.json())

Create a directory specified by the fileType

// create a directory if it doesn't already exists using the file system module
const createDirIfNotExists = (dir) => {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true })
    }
}

Multer Storage

// set storage engine for multer
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        const fileType = req.body.fileType
        const uploadPath = `./uploads/${fileType}`

        createDirIfNotExists(uploadPath)

        cb(null, uploadPath)
    },
    filename: (req, file, cb) => {
        cb(null, `${Date.now()}-${file.originalname}`);
    }
})

const upload = multer({ storage: storage })

app.post middleware

app.post('/storeOnHDD', upload.single('file'), (req, res) => {
    console.log(req.body) // here we receive the file and the fileType correctly
    if (!req.file) {
        return res.status(400).send('No file uploaded');
    }

    res.status(200).send({
        message: 'File uploaded successfully',
        file: req.file,
    });
})

My folder output

Folder structure

Expected output A different folder for every file type

2

1 Answer 1

1

It's because fileType field has not been processed yet, and that's why it's undefined.

On client, change the order of fields, and add fileType field to the form before file field:

// add fileType first
formData.append('fileType', 'video')
formData.append('file', file)

axios.post('http://localhost:5000/storeOnHDD', formData, {

see:

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

https://www.npmjs.com/package/multer#diskstorage

2
  • @DarkBee I explained the problem clearly enough, there was no need for it
    – traynor
    Commented Jun 18 at 8:28
  • Yes there was, otherwise I wouldn't have commented for more clarification right? At least now you have provided a source
    – DarkBee
    Commented Jun 18 at 8:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.