1

i want to upload the file into a folder which should be get from form data submit by user. which is 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;
        }         
    });
});

How can I create a folder with the name req.body.coursename for file upload?

1 Answer 1

2

You can't but you can move the file to other locations after the file is uploaded. You could make your storage object a module and change the directory dynamically via 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);
    }
}

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

OR you can use 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
});
Sign up to request clarification or add additional context in comments.

2 Comments

is it posible other than multer
i am new in nodejs. what you mean by init ? .please explain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.