Node JS Multer Rename Uploaded File Example

Hey,

This tutorial is focused on node multer rename file name. you will learn multer change filename example. if you want to see example of multer change file name then you are a right place. this example will help you node js change file name uploaded. Follow bellow tutorial step of how to rename filename multer nodejs.

I will give you simple solution with full example of how to change file name in multer node js. let’s see solution with example:

Solution:

const storage = multer.diskStorage({

destination: function(req, file, cb) {

cb(null, 'uploads/');

},

filename: function(req, file, cb) {

cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));

}

});

var upload = multer({ storage: storage })

Example:

const express = require('express');

const multer = require('multer');

const path = require('path');

const fs = require('fs');

const app = express();

const storage = multer.diskStorage({

destination: function(req, file, cb) {

cb(null, 'uploads/');

},

filename: function(req, file, cb) {

cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));

}

});

var upload = multer({ storage: storage })

app.get('/', (req, res) => {

res.sendFile(__dirname + '/index.html');

});

app.post('/', upload.single('image'),(req, res) => {

const { filename: image } = req.file;

res.redirect('/');

});

app.listen(3000);

I hope it can help you…

Leave a Comment