Rahul SK
Rahul SK

Reputation: 422

nodejs multer image upload : retain file name and extension

I have a node.js express code below to upload a image and store into a default folder.

I realised that the file gets renamed and the extension is lost. can some one help me fix this error?

1.How to retain extension and file name

  1. if a zip file is upload, i want to unzip it and upload it

    const __basefolder = "C:/Users/user/Desktop";
    const express = require('express');
    const multer = require('multer');
    const upload = multer({dest: __basefolder + '/uploads/images'});
    const app = express();
    const PORT = 3000;
    
    app.use(express.static('public'));
    app.post('/upload', upload.single('file'), (req, res) => {
        if(req.file) {
            res.json(req.file);
        }
        else throw 'error';
    });
    app.listen(PORT, () => {
        console.log('Listening at ' + PORT );
    });
    

Upvotes: 1

Views: 1198

Answers (1)

eol
eol

Reputation: 24565

You can define a filename-option in your disk-storage setup, which lets you choose your filename arbitrarily. Since you want the original file-name, you can use file.originalname (note that using this an existing file with the same name will be overwritten though):

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, __basefolder + '/uploads/images');
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname);
    }
})

const upload = multer({storage});

Regarding the second question: this has been answered before, see this or that for example.

Upvotes: 2

Related Questions