multer icon indicating copy to clipboard operation
multer copied to clipboard

Cannot read property 'path' of undefined"

Open onlineaid opened this issue 2 years ago • 0 comments

###nodejs multer diskstorage to delete file after saving to disk

I saw this issue but I can't get an exact solution.

upload an image file through multer but the problem is I can't delete my image path. I try a lot of different ways. I use node js fs like fs.unlink(req.file.path, (err) => console.log(err); here are some error patterns.

[NOTE] I use postman. I don't use npm express-fileupload

-👉 01 "msg": "The "path" argument must be of type string or an instance of Buffer or URL. Received type number (NaN)"

-👉 02 "msg": "Cannot read property 'filename' of undefined"

-👉 03 "msg": "Cannot read property 'path' of undefined"

-👉 04 "msg": "The "path" argument must be of type string or an instance of Buffer or URL. Received undefined"

middleware upload.js

`const multer = require('multer') const path = require('path')

const FILE_TYPE_MAP = { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/jpg': 'jpg' }

const storage = multer.diskStorage({ destination: function (req, file, cb) { const isValid = FILE_TYPE_MAP[file.mimetype]; let uploadError = new Error('invalid image type');

    if(isValid) {
        uploadError = null
    }
  cb(uploadError, 'upload')
},
filename: function (req, file, cb) {
  cb(null, 'online' + '-' + Date.now() + path.extname(file.originalname))

}

})

const upload = multer({ storage: storage, limits: { fieldSize: 10 * 1024 * 1024 }, // 1mb

fileFilter: (req, file, cb) => { if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") { cb(null, true); } else { cb(null, false); // return res.status(400).json({msg: "Size too large."})

  let err = cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
  return err;
}

} })

module.exports = upload; `

My router I use upload middleware what about delete ??

Router system

` const router = require('express').Router(); const proCtrl = require('../controller/proCtrl'); const upload = require('../middleware/upload')

router.post('/product', upload.single('image'), proCtrl.createProduct) router.delete('/product/del/:id', proCtrl.deleteProduct) router.get('/product/:id', proCtrl.getProduct)

module.exports = router;

` Here I use my controller functionnality

my controller.js ` // model const Product = require('../models/productModel');

//fs const fs = require('fs');

const proCtrl = { createProduct: async(req, res) => { try {

        const file = req.file;
        if(!file) return res.status(400).send('No image in the request')
        const fileName = file.filename
        const basePath = `${req.protocol}://${req.get('host')}/upload/`;
        
        const product = await Product.create({
            title: req.body.title,
            image: `${basePath}${fileName}`,
        })

        res.status(201).json({
            success: true,
            product
        })
                    
    } catch (err) {
        return res.status(500).json({msg: err.message}) 
    }
},
deleteProduct: async(req, res,) => {
    try {
        let product = await Product.findById(req.params.id);

        if (!product) {
            return res.status(400).json({
                success : false,
                message : 'Product not found'
            })
        };

        await product.remove();

        let pt = req.file.path
        console.log(pt);

        fs.unlink( pt, (err)=> console.log(err))
    
        res.status(200).json({
            success: true,
            message: 'Product is deleted.'
        })
        
    } catch (err) {
        return res.status(500).json({msg: err.message})
        
    }
},
getProduct : async(req, res)=>{
    try {

        let product = await Product.findById(req.params.id);

        if (product) {
            return res.status(400).json({
                success : true,
                message : product
            })
        };

        if (!product) {
            return res.status(400).json({
                success : false,
                message : 'Product not found'
            })
        };


        
    } catch (error) {
        return res.status(500).json({
            msg: error.message
        })
    }
}    

}

module.exports = proCtrl; `

mongoose collection

models.js ` const mongoose = require('mongoose')

const productScheme = new mongoose.Schema({ title : { type: String, required: [true, 'Plz give a title'] },

image: {
    type: String,
    default: ''
}

}, { timestamps: true })

module.exports = mongoose.model('Product', productScheme)

`

Now can anyone help me to fix this? It's really a big problem for me to go ahead without solving the issue!

onlineaid avatar Mar 25 '22 05:03 onlineaid