File uploading with Express 4.0: req.files undefined

后端 未结 9 1763
感动是毒
感动是毒 2020-11-22 10:10

I\'m attempting to get a simple file upload mechanism working with Express 4.0 but I keep getting undefined for req.files in the app.post

9条回答
  •  孤街浪徒
    2020-11-22 11:06

    multer is a middleware which handles “multipart/form-data” and magically & makes the uploaded files and form data available to us in request as request.files and request.body.

    installing multer :- npm install multer --save

    in .html file:-

    in .js file:-

    var express = require('express');
    var multer = require('multer');
    var app = express();
    var server = require('http').createServer(app);
    var port = process.env.PORT || 3000;
    var upload = multer({ dest: 'uploads/' });
    
    app.use(function (req, res, next) {
      console.log(req.files); // JSON Object
      next();
    });
    
    server.listen(port, function () {
      console.log('Server successfully running at:-', port);
    });
    
    app.get('/', function(req, res) {
      res.sendFile(__dirname + '/public/file-upload.html');
    })
    
    app.post('/upload', upload.single('avatar'),  function(req, res) {
      console.log(req.files); // JSON Object
    });
    

    Hope this helps!

提交回复
热议问题