Upload a file in NodeJs with Multer and change name if the file already exists

浪尽此生 提交于 2019-12-11 00:37:51

问题


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



来源:https://stackoverflow.com/questions/36648395/upload-a-file-in-nodejs-with-multer-and-change-name-if-the-file-already-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!