简体   繁体   中英

Image is overwriting in local Folder using multer in Node.js app

I am trying to upload image in Local folder as well as saving the image name in MongoDB.

var uploadDir=__dirname+'/uploads';
 var images=Date.now()+'.jpg';
var storage=multer.diskStorage({

    destination:function(request, file, callback){
        callback(null, uploadDir);
        },
        filename:function(request, file, callback){
            console.log(file);
            callback(null, images);
            }
    });
    var upload=multer({storage:storage}).single('image');

Above is the multer configuration code. The problem is that while I insert an image then it is saving successfully in local folder but again I save another image then the new image is overwriting the previous image in folder. But in MongoDB images name are differents.

You have added images value as Date.now on top the file which will executes once at the time of loading .

Try below code.

var uploadDir=__dirname+'/uploads';

var storage= multer.diskStorage({

destination:function(request, file, callback){
    callback(null, uploadDir);
    },
    filename:function(request, file, callback){
        var images = '.jpg';
        console.log(file);
        images += Date.now()+images;
        callback(null, images);
        }
});
var upload=multer({storage:storage}).single('image');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM