Upload a file in NodeJs with Multer and change nam

2019-07-13 11:17发布

问题:

I need to upload a file from my client to a Node server (I use Multer to perform this task).

The requirement is that if a file with the same name already exists on the server I need to change the name of the new file. I use Node fs.stat to check for the existence of a file with the same name.

I must be doing something wrong since fs.stat always tells me that there is no file with the same name when in fact it is there (I end up overwriting the old file with the new one).

Here is the code.

       var imagesDirectory = 'images';
        var imageDir = '/' + imagesDirectory + '/';
        var storageDisk = multer.diskStorage({
            destination: imagesDirectory,
            filename: function (req, file, callback) {
                let uploadedFileName;
                fs.stat(imageDir + file.originalname, function(err, stat) {
                    if (err==null) {
                        uploadedFileName = Date.now() + '.' + file.originalname;
                    } else if(err.code == 'ENOENT') {
                        uploadedFileName = file.originalname;
                    } else {
                        console.log('Some other error: ', err.code);
                    }
                    callback(null, uploadedFileName)
                });
            }
        })
        var uploadImage = multer({ storage: storageDisk, limits: {fileSize: 1000000, files:1}, }).single('imageFile');
        router.post('/image', function(req, res) {
            uploadImage(req, res, function (err) {
                if (err) {
                    // An error occurred when uploading
                    console.log(err);
                }
// do something to prepare the response and send it back to the client
prepareResponseAndSendItBack(req.file.filename, imageDir, res, err);
            })
        })

回答1:

I believe that fs.exists is more suitable for that task.

fs.exists(imageDir + file.originalname, function(exists) {
    let uploadedFileName;
    if (exists) {
        uploadedFileName = Date.now() + '.' + file.originalname;
    } else {
        uploadedFileName = file.originalname;
    } 
    callback(null, uploadedFileName)
});

Also make sure that you pass the fullpath (or a relative one to the current file) of the file