使用Multer在NodeJs中上载文件,并更改名称(如果文件已存在) [英] Upload a file in NodeJs with Multer and change name if the file already exists

查看:541
本文介绍了使用Multer在NodeJs中上载文件,并更改名称(如果文件已存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将文件从客户端上传到节点服务器(我使用Multer执行此任务).

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

要求是,如果服务器上已经存在具有相同名称的文件,则需要更改新文件的名称.我使用Node fs.stat来检查是否存在同名文件.

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.

我肯定做错了,因为fs.stat总是告诉我实际上没有文件(我最终用新文件覆盖了旧文件).

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).

这是代码.

       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);
            })
        })

推荐答案

我相信fs.exists更适合该任务.

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

这篇关于使用Multer在NodeJs中上载文件,并更改名称(如果文件已存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆