Home > Software design >  Multer file buffer missing
Multer file buffer missing

Time:11-11

the req.file property returned from the following does not contain a buffer property (https://www.npmjs.com/package/multer). So when I try to access req.file.buffer it returns undefined. Can someone help to explain. `

const multer = require('multer')
const uploadtest = multer({
    dest: 'avatar'
})

router.post('/uploadtest', uploadtest.single('upload'), (req, res)=>{
    console.log(req.file)
    req.user.avatar = req.file.buffer
    await req.user.save()
    
    res.send()
    }, (error, req, res, next)=>{ 
        res.status(400).send({error: error.message})
    }
)

` the output from console.log(req.file) is:

{
  fieldname: 'upload',
  originalname: 'sample-doc-file.doc',
  encoding: '7bit',
  mimetype: 'application/msword',
  destination: 'avatar',
  filename: 'e488d6205717d45f397782b79d45fd8e',
  path: 'avatar\\e488d6205717d45f397782b79d45fd8e',
  size: 22528
}

CodePudding user response:

This is expected, since you are using DiskStorage - the code initializes multer with a "dest" option, so it will save the files locally. Take a look at the multer README - the API doc says in the "Note" column that buffer is for MemoryStorage only.

Therefore, you must decide - do you wish to save the files to the filesystem (and get the path), or load into memory in full (and get the buffer)? In the latter case, the README contains a section called "MemoryStorage" that demonstrates how to configure multer:

const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
  • Related