Good day, I'm new to coding & facing a weird problem that I can't solve by my own, please see my code below.
I am working on a E-commerce website and I have written the same code as is shown in the video but still face this issue
const router = require('express').Router()
const cloudinary = require('cloudinary')
const auth = require('../middleware/auth')
const authAdmin = require('../middleware/authAdmin')
const fs = require('fs')
// we will upload image on cloudinary
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.CLOUD_API_KEY,
api_secret: process.env.CLOUD_API_SECRET
})
// Upload image only admin can use
router.post('/upload',auth , authAdmin, (req, res) =>{
try {
if(!req.files || Object.keys(req.files).length === 0)
return res.status(400).json({msg: 'No files were uploaded.'})
const file = req.files;
console.log(file)
if(file.size > 1024*1024) {
removeTmp(file.tempFilePath)
return res.status(400).json({msg: "Size too large"})
}
if(file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png'){
removeTmp(file.tempFilePath)
return res.status(400).json({msg: "File format is incorrect."})
}
cloudinary.v2.uploader.upload(file.tempFilePath, {folder: "test"}, async(err, result)=>{
if(err) throw err;
removeTmp(file.tempFilePath)
res.json({public_id: result.public_id, url: result.secure_url})
})
} catch (err) {
return res.status(500).json({msg: err.message})
}
})
const removeTmp = (path) =>{
fs.unlink(path, err=>{
if(err) throw err;
})
}
module.exports = router
I am getting an error :
{
"msg": "The \"path\" argument must be of type string or an instance of Buffer or URL. Received undefined"
}
I'm using a console on line 21 :
{
'': {
name: 'adidas.jpg',
data: <Buffer >,
size: 12302,
encoding: '7bit',
tempFilePath: 'C:\\Users\\back-end\\tmp\\tmp-1-1615519087170',
truncated: false,
mimetype: 'image/jpeg',
md5: '262073b93fdb5aa3f9dff6b5a010f2ed',
mv: [Function: mv]
}
}
I am not able to find the solution for my error because I am new to coding
ThankYou for helping