0

What i want to do is to upload files to the server after some tests made at the req.body . I am familiriar with this question that seems to be the exact problem but can't manage to get things work. My code is:

var express = require('express'); 
var router = express.Router();
var fs=require('fs') 
var multer = require('multer'); 
var config = require(__dirname +'/../config.js') 
var rootArchiveFolder = config.rootFolder 

var getFields = multer(); 

router.post('/:module', getFields.any(), (req, res, next)=> { 
    var module = req.params.module; 

    console.log("req.body", req.body); 
    console.log("req.params.module", req.params.module); 

    switch (module){ 
        case 'archive': 

    var makeDBEntry  = require('../models/makeDBEntry.js'); 
        makeDBEntry.makeArchiveEntry(req.body) 
        .then( responseData => { 
            console.log("all ok") 

            var tmpdir = req.body.p_receive_date; 
            var dir = tmpdir.replace(/\//g, "-"); 
            dir = rootArchiveFolder + dir; 
            if (!fs.existsSync(dir)){ 
                fs.mkdirSync(dir); 
            } 

            var storage = multer.diskStorage({ 
                destination: function(req,file,cb){ 
                    cb(null,dir); 
                }, 
                filename: function(req,file,cb){ 
                    // cb(null,req.body.p_doc_no); 
                    cb(null, req.files[0].originalname); 
                } 
            }) 
            var upload = multer({storage:storage}); 
            // upload.any(req, res, next); doesnt seems to work
            //how can i upload my files here after all my test are done?

            res.end(); 
        }) 
        .catch( e => { 
            res.status(500).send(response.message); 
            console.log(e.message); 
        }); 
        res.send("ok") 
        break; 
    } 
});

What am i missing here??

Community
  • 1
  • 1
prieston
  • 1,426
  • 2
  • 18
  • 39
  • You can see and example with multer here: http://stackoverflow.com/questions/31748936/how-to-send-files-with-superagent/39938312#39938312 – Hosar Feb 12 '17 at 14:54

1 Answers1

0

The way I managed to solve it is upload the files to a tmp folder, then make the checks and if true, move the files in the correct folder, else I delete them. It's the best i could do.. I know that the multer.js provides code that is to be executed as a middleware so the point of runnig a test and upload after is not consistent with the middleware logic. I think I am searching for a backdoor here. The question remains..

prieston
  • 1,426
  • 2
  • 18
  • 39
  • 1
    In this SO answer, I have demonstrated how to upload a file to a certan location using multer with a post endpoint http://stackoverflow.com/questions/34590386/multer-create-new-folder-with-data/34936277#34936277 – Raf Feb 26 '17 at 19:48