Home > Blockchain >  uploading two files from two fields with multer as middleware
uploading two files from two fields with multer as middleware

Time:03-26

i'm trying to upload two files with different file extensions with multer from two fields but when i try it with postman the result always for the file is null, what is the solution for my problem? here is my code

middleware/uploadEpub

const multer = require('multer')

exports.uploadEpub = (epubFile, coverFile) => {
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "uploads")
    },
    filename: function (req, file, cb) {
        cb(null, Date.now()   '-'   file.originalname.replace(/\s/g, ""))
    }
})

const upload = multer({
    storage
}).fields([{name: "bookFile", maxCount: 1},{name: "coverFile", maxCount: 1}])
}

controller/book

exports.addBook = async (req, res) => {
try {
    const { ...data } = req.body

    const newBook = await book.create({
        ...data,
        bookFile: req.file,
        coverFile: req.file
    })
    let bookData = await book.findOne({
        where: {
            id: newBook.id
        },
        attributes:{
            exclude: ['createdAt','updatedAt']
        }
    })

    bookData = JSON.parse(JSON.stringify(bookData))
    res.send({
        status: "Success",
        Book: {
            ...bookData
        }
    })
} catch (error) {
    console.log(error)
    res.status(500).send({
        status: "Failed",
        message: "Server Error"
    })
}
}

CodePudding user response:

try to upload the file as form-data in postman, and put the key with the same name that you have set in multer, the postman will look like this

CodePudding user response:

Multer set up

const multer = require('multer')
const path = require('path')
const { nanoid } = require('nanoid')

//Set Storage Engine
const storage = multer.diskStorage({
    destination: './public/uploads/',
    filename: (req, file, callback) => {
        const id = nanoid(6)
        const newFilename = `${file.fieldname}_${id}-${new Date().toISOString().replace(/:/g, '-')}${path.extname(file.originalname)}`
        callback(null, newFilename)
    }
})

const upload = multer({
    storage: storage,
    limits: { fileSize: 5572864 }, // up to 5.5 MB
    fileFilter: (req, file, callback) => {
        checkFileType(file, callback)
    },
})

//Check File Type
const checkFileType = (file, cb) => {
    //Allowed extensions
    const fileType = /jpeg|jpg|png|gif|svg|pdf|epub/

    //Check extension
    const extname = fileType.test(path.extname(file.originalname).toLowerCase())

    //Check mimetype
    const mimetype = fileType.test(file.mimetype)

    if (extname && mimetype) {
        return cb(null, true)
    } else {
        return cb('Error: wrong file type!')
    }
}

module.exports = upload

/***** middlewares.js *****/

module.exports.imageUploader = (req, res, next)=>{
    const files = req.files
    const uploadedFiles = []
    for (var i = 0; i <images.length; i  ){
        uploadFiles.push('https://yourserver.com/public/uploads/'   files[i].filename)
    }
    req.uploadFiles = uploadFiles.toString() //appending files to req
    next()
    return
}

/**** index.js or app.js ****/ //where your routes are defined

router.post('/books/add', upload.array('images', 10), imageUploader, book.addBook) // allowing up to 10 files to be uploaded, calling imageUploader as a middleware

/*** Controllers/book ***/

exports.addBook = async (req, res) => {
   const uploadedFiles = req.uploadFiles; //catching files from imageUploader middleware

   // ... rest of your code
}
  • Related