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
}
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 })
I experienced the same issue, req.file.buffer was undefined. As Robert pointed out, I was using the dest option for multer . This is what worked for me:
const multer = require('multer');
const upload = multer();
router.post('/', upload.single('image_file'), myController)
then on myController
var buffer = req.file.buffer;
要获得await
的好处,您必须在(req, res) => {}
之前编写async
If we use the dest
option, multer stores the image in that directory.
But if we do not use it, then multer does not save the image in any directory. It just passes the data( req.file
) through our function so we can do something with it.
So we have two options:
New 2.0 no longer requires storage. Below worked for me
const multer = require('multer')
const upload = multer()
app.post('/upload', upload.single('audiofile'), async (req,res) => {
const filename = `my ${x} upload `
const bucketname = 'name-bucket'
const file = req.file.buffer
console.log('FILE', file)
const link = await uploadAudio(filename, bucketname, file)
console.log(link)
res.send('uploaded successfully')
})
Output Code
ETag: '"2c21f2b5d2893279acc3349e8a3881aa"',
Location: 'https://name-bucket.s3.amazonaws.com/my%20first%20upload',
key: 'my first upload',
Key: 'my first upload',
Bucket: 'name-bucket'
Was able to get location of file so I can download
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.