Search code examples
node.jsamazon-s3multernode-rest-clientmulter-s3

Upload and redirect page using multer


I am having a problem to redirect the page after a successful file upload using multer. With the file upload i am also saving some text into the database. Here's my code.

Question :

When the file and the contents are saved in the DB how can I redirect the page to a new URL ?

I am currently using res.redirect('product/item'); but nothing happens. I also tried using res.render, but the page did not redirect.

Multer method to upload a file to Amazon S3

var upload = multer({
    storage: multerS3({
    s3: s3,
    bucket: 'nameofthebucket',
        metadata: function (req, file, cb) {
            var ext = file.originalname.split('.').pop();

            cb(null, {fieldName: 'file.fieldname' + '.' + ext});
        },
        filename: function(req,file,cb){
            var ext = file.originalname.split('.').pop();
                           cb(null,   Date.now() + '.' + ext);
        },
            key: function (req, file, cb) {
                var ext = file.originalname.split('.').pop();
                cb(null,   Date.now() + '.' + ext);
        }
    })
})


var upload = upload.array('fileup', 10);

The code responsible to upload the file and the content

router.post('/uploadfileandcontent',function(req,res,next){

    upload(req,res,function(err) {
        if(err) {
        } else {


            saveRecordsToDB(req, function(err,data){
                if (err) {

                    res.redirect('/errorpage');
                } else {
                    res. redirect('product/item');

                }

            });


        }

    });



});

Function that saves records to DB and makes the callback

function saveRecordsToDB (req, callback){

            var args = {
                data: {
                        "name" : req.body.name, //
                        "age" : req.body.age

                },

                headers: { "Content-Type": "application/json" }

            };


            // registering remote methods 
            client.registerMethod("postMethod", "http://url/uploadfileandcontent", "POST");

            var req =client.methods.postMethod(args, function (data, response) {


                callback(null, 'success?');

            });

            req.on('error', function (err) {
                console.log('error');


            });
}

Note: I also made use of NODE REST CLIENT to send http request.


Solution

  • This should work. Tell me if it doesn't.

    router.post('/uploadfileandcontent', function(req,res,next){
    
        upload(req,res,function(err) {
            if(err) {
                res.send('Error while uploading.');
            }
    
            saveRecordsToDB(req, function(err,data){ 
                if (err) {
                  console.log(err);
                  req.flash('error', { msg: 'Error while saving data.' }); // Flash message -> need to configure your template to show it
                } 
    
                // Saved to DB
                req.flash('success', { msg: 'Saved' });
                res.redirect('/product/item'); // go to this page
    
            });
    
        });
    
    
    });
    

    UPDATE You will need to include const flash = require('express-flash'); to use flash message. Then you can load it to your app like this: app.use(flash());. The app is express loaded like this: const app = express();.

    In your HTML you will access it in an array. Example using Jade:

    //success
    if messages.success
        for success in messages.success
            div #{success.msg} // Saved 
    //Error
    if messages.errors
        for error in messages.errors
            div #{error.msg} // Error while saving data.