How to properly handle req.files in node post request using multer and typescript
I Fixed This Using Below Code :
req.body.thumbnails = req.files
const {enName , fullName , type , price , desc , category , instrument , thumbnails } = req.body
await new ProductModel().createProduct({
enName , fullName , type , price , desc , category , instrument , sellCount , thumbnails
})
The problem looks like it arises because req.files
is not what you think it is.
Looking at the multer documentation, it appears that the type of req.files
will vary depending on how you set up the multer middleware.
The basic usage section of the documentation shows three different possibilities:
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['avatar'][0] -> File
// req.files['gallery'] -> Array
//
// req.body will contain the text fields, if there were any
})
You haven't shown us which form of the multer middleware you are using, but the error you're getting suggests that you're using the third option instead of the second.