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

问题描述 投票:0回答:3

如何同时上传不同文件夹中的同一张图片? 我在下面尝试过,但没有成功,但是当上传到一个文件夹中时,它会工作。

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>
node.js file-upload imagemagick multer
3个回答
1
投票

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


0
投票

对于相同的要求,下面的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");
        });
    }); 

0
投票

使您的 multer 代码如下所示,它应该可以工作:

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);
    },
});
© www.soinside.com 2019 - 2024. All rights reserved.