Search code examples
javascripthtmlnode.jsmulter

Image uploaded in my folder without extension with node js and multer


I have a weird problem with node and multer.

My script to upload an image is working, but the images are being uploaded without the extension (jpeg, png, etc). Just like that: 4a8a1400d04b5ccdfdb829aa5ee62763

If I add an extension (jpeg) to the image, then it's displayed.

My code is like that:

    const multer  = require('multer');

    var upload = multer({ dest: __dirname +'/uploads/' });

    app.post('/test.html', upload.single('avatar'),function (req,res,next){
        
       console.log("minetype"+req.file.mimetype);
       res.render('test', {})       
    });

And my form:

    <form action="/test.html" method="post" enctype="multipart/form-data" name="monForm">
       <input type="file" name="avatar" />        
       <input type="submit" value="Upload">       
    </form>

Solution

  • you can configure filename with this for exemple : which will preserve the original extension and still generate a random name using uniqid package. (feel free to replace it with something else if needed)

    const uniqid = require('uniqid');
    const path = require('path');
    const multer  = require('multer');
    
    let upload = multer({
        storage: multer.diskStorage({
            destination: function (req, file, cb) {
                cb(null, `${__dirname}/uploads/`);
            },
            filename: function (req, file, cb) {
                cb(null, uniqid() + path.extname(file.originalname));
            },
        }),
    });