如何在多个文件夹中上传相同的图像Nodejs multer

mitkmikd  于 12个月前  发布在  Node.js
关注(0)|答案(3)|浏览(135)

如何上传相同的图像在不同的文件夹在同一时间?我尝试了下面,但不工作,但当上传在一个文件夹中,它会工作。

var multer  = require('multer');

const storage = multer.diskStorage({

    destination: (req, file, cb) => {

        cb(null, 'public/images/image')

        cb(null, 'public/images/pic')
    },

    filename: (req, file, cb) => {

        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)

        cb(null, file.fieldname + '-' + uniqueSuffix+'.png')

    }

});

const cpUpload = multer({ storage: storage });

字符串
在前端:

<input type = "file" name="image" />

<button>Upload</button>

zzzyeukh

zzzyeukh1#

Multer期望从destination()-函数得到一个文件名。所以这种方法不起作用。你可以在destination()中传递单个目录,然后在你的控制器中,在multer处理完文件上传请求后,使用fs.copyFile()将上传的文件从一个位置复制到其他位置。

j8yoct9x

j8yoct9x2#

对于同样的需求,下面的nodejs代码对我来说是有效的。

pool.query('SELECT first_name FROM users where user_pk = 1', (err,rows) => {
      if(err) throw err;
        rows.forEach( (row) => {
        //console.log(`${row.first_name}`);
        var fname = (`${row.first_name}`);
        console.log('First Name is : ' + fname);
        //let fname = req.first_name;
    
    
    var dateObj = new Date();
    //var month = dateObj.getUTCMonth() + 1; //months from 1-12
    var year = dateObj.getUTCFullYear();
    var month = dateObj.toLocaleString('default', { month: 'long' });
    var day = dateObj.getUTCDate();
    
    
    datewise = "datewise" + "/" + year + "/" + month + "/" + day + "/" + fname;
    empwise  = "empwise"  + "/" + fname + "/" + year + "/" + month + "/" + day;
    
        });`enter code here`
      });  
      
    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        let Id = req.body.id;
        let datewisepath = `/RestAPIUpload/${datewise}`;
        let empwisepath = `/RestAPIUpload/${empwise}`;
            fs.mkdirsSync(datewisepath);
            fs.mkdirsSync(empwisepath);     
        cb(null, datewisepath);
        cb(null, empwisepath);
        // callback(null, 'uploads/' + req.user.id);
      },
     /* filename: function (req, file, callback) {
        callback(null, file.originalname + '-' + Date.now());
      }
    });
    */
    
    filename: function (req, file, cb) {
        // console.log(file);
        let extArray = file.mimetype.split("/");
        let extension = extArray[extArray.length - 1];
        cb(null, file.originalname + '-' + Date.now() + "." + extension);
        console.log(req.file);
     }
    })
    var upload = multer({ storage : storage }).array('dataFile',50);
    
    app.post('/upload',function(req,res){
        upload(req,res,function(err) {
            console.log(req.body);
            console.log(req.files);
            if(err) {
                return res.end("Error uploading file.");
            }
            res.end("File is uploaded");
        });
    });

字符串

pexxcrt2

pexxcrt23#

使你的多重代码如下,它应该是工作:

const currentTIme =  Date.now();
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        const uploadDirs = ['uploads', 'uploads/posts'];
        uploadDirs.forEach((dir) => {
            const destinationPath = dir;
            cb(null, destinationPath);
        });
    },
    filename: (req, file, cb) => {
        cb(null, currentTIme + '-' + file.originalname);
    },
});

字符串
如果你想用不同的名字保存,那么它应该是这样的:

const currentTIme =  Date.now();
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        const uploadDirs = ['uploads', 'uploads/posts'];
        uploadDirs.forEach((dir) => {
            const destinationPath = dir;
            cb(null, destinationPath);
        });
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + + '-' + file.originalname);
    },
});

相关问题