如何使用nodejs中的multer动态创建用于文件上载的用户定义文件夹?

时间:2016-07-29 06:36:24

标签: node.js multer

我想将文件上传到一个文件夹中,该文件夹应该从用户提交的表单数据中获取。这是req.body.coursename

/*conditions for directory check*/
var isvalidate = function (data) {
    var data = data;
    var dir = '../uploads'+'/'+data;
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
        return dir;
    } else {
        return dir; 
    }
};  

/*multer*/

var date = moment().format('YYYY-MM-DD');
var storage = multer.diskStorage ({
    destination: function (req, file, callback) {
        console.log("filename upload",file.originalname);  
        callback(null, isvalidate(req.body.coursename));
    },
    filename: function (req, file, callback) {
        //console.log("filename upload",file.originalname);
        callback(null, date+ '-' +file.originalname );
    }
});
var data = multer({ storage : storage }).any();

/*file upload*/

router.post('/create',function(req, res) {
    console.log(req.body);
    data(req, res, function(err) {
        console.log(req.body);
        //isvalidate (req.body.coursename);
        if (err) {
            res.json({error_code:1,err_desc:err});
            return;
        }         
    });
});

如何为文件上传创建名为req.body.coursename的文件夹?

1 个答案:

答案 0 :(得分:1)

您可以,但您可以在上传文件后将文件移动到其他位置。您可以将存储对象作为模块并通过init

动态更改目录
var multer = require('multer'); //  middleware for handling multipart/form-data,
// Constructor 
module.exports = function (name) {
    try {
        // Configuring appropriate storage 
        var storage = multer.diskStorage({
            // Absolute path
            destination: function (req, file, callback) {
                callback(null, './uploads/'+name);
            },
            // Match the field name in the request body
            filename: function (req, file, callback) {
                callback(null, file.fieldname + '-' + Date.now());
            }
        });
        return storage;
    } catch (ex) {
        console.log("Error :\n"+ex);
    }
}

或使用busboy

var Busboy = require('busboy');
var fs = require('fs');
app.post('.....',fucntion(req, res, next){
var busboy = new Busboy({ headers: req.headers });
busboy.on('field', function(fieldname, val) {

  req.body[fieldname] = val;
});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
fstream = fs.createWriteStream("path/desiredImageName");
    file.pipe(fstream);
    fstream.on('close', function() {

       file.resume();

 });
})
 return req.pipe(busboy);
})

或者您可以使用changedest

app.post('/api/:type', multer({
dest: './uploads/',
changeDest: function(dest, req, res) {
var newDestination = dest + req.params.type;
var stat = null;
try {
    stat = fs.statSync(newDestination);
} catch (err) {
    fs.mkdirSync(newDestination);
}
if (stat && !stat.isDirectory()) {
    throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"');
}
return newDestination
}
}), function(req, res) {
 //set your response
});