Search code examples
node.jsexpressmeanjsmulter

Upload file to project specific directory dynamically in multer


I am trying to add a file upload feature in my MEAN.js application. I made use of multer, but it places all the files directly in the destination specified at the time of initializing multer. I want to upload files to directories specific to the program for which they are being uploaded (of course create directory dynamically if it doesn't exist). Where should I specify the custom logic of creating directories on the fly and placing files in them.


Solution

  • I think the best solution to this problem is to use busboy, which let's you store your images in your desired location.

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