2016-08-12 26 views
2

我在使用multer上傳成功的文件後重定向頁面時出現問題。隨着文件上傳,我也將一些文本保存到數據庫中。這是我的代碼。使用多波器上傳和重定向頁面

問:

當文件和內容保存在數據庫中我怎麼能在頁面重定向到一個新的網址是什麼?

我目前使用res.redirect('product/item');但沒有任何反應。我也嘗試使用res.render,但頁面沒有重定向。

Multer方法將文件上傳到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); 

負責上傳的文件和內容

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


      }); 
} 

注意:我也使用NODE REST CLIENT來發送http請求。

回答

1

這應該工作。告訴我如果沒有。

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 您將需要包括const flash = require('express-flash');使用閃光燈消息。然後你可以像這樣加載它到你的應用程序:app.use(flash());appexpress像這樣加載:const app = express();

在您的HTML中,您將在數組中訪問它。例如,使用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. 
+0

我給它一個嘗試。你能告訴我如何從HTML頁面中檢索'msg'嗎? – Illep

+0

更新了更多細節 – agaezcode