如何在NodeJS / Multer中以相同的形式发送字段和文件?

时间:2018-02-11 13:34:25

标签: node.js express multer

我的问题是,当我发布到/ new时,我无法获取req.body和req.file对象,但一切都很好,文件正在我的文件夹中上传。我无法访问req.body和req.file对象。当我在控制台中记录req.body时它会返回[object Object],而对于req.file,它会记录undefined。

我已经完成了一些研究,我发现你不能用body-parser对multipart / form-data进行编码,但是我需要它,因为没有它我就无法发送文件。

var router = require('express').Router(),
    multer = require('multer'),
    path = require('path'),
    passport = require('passport'),
    middleware = require('../middleware'),
    User = require('../models/User'),
    Ad = require('../models/Ad');

// Storage setup
var storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function(req, file, done) {
    done(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Upload setup
var upload = multer({
  storage: storage,
  limits: {
    fileSize: 3000000
  }
}).single('banner');

// Check file type
function checkFileType(file, callback) {
  // Allowed extensions
  var fileTypes = /jpeg|jpg|png|gif/;
  // Check extention
  var extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime type
  var mimeType = fileTypes.test(file.mimetype);

  if (mimeType && extname) {
    return callback(null, true);
  }
  callback(null, false);
}

router.get('/new', middleware.isLoggedIn, function(req, res) {
  res.render('new');
});

router.post('/new', middleware.isLoggedIn, function(req, res) {
  var adObj = {
    owner: req.user,
    url: req.user.url,
    paymentType: req.body.paymentType,
    transactionId: '',
    banner: ''
  };

  if (adObj.paymentType === 'paid') {
    adObj.transactionId = req.body.transactionId;
  }

  upload(req, res, function(err) {
    if (err) {
      req.flash('error', err.message);
      return res.redirect('/new');
    }
    adObj.banner = '/uploads/' + req.file.filename;
  });

  var ad = new Ad(adObj);
  ad.save();

  req.flash('success', 'Successfully added new ad.');
  res.redirect('/');
});
<form class="main-form" action="/new" method="POST" enctype="multipart/form-data">
      <input type="url" name="url" placeholder="Website URL" required>
      <select class="select-ad-type" name="paymentType">
        <option value="free" selected>Free Ad</option>
        <option value="paid">Sponsored Ad - $10</option>
      </select>
      <div class="transaction-section">
        <p>Send $10 to example@gmail.com and type your transaction id below. Your ad will be displayed in the "SPONSORED ADS" section in less than 24 hours.</p>
        <input type="text" name="transactionId" placeholder="Transaction Id">
      </div>
      <input type="file" name="banner" required>
      <button><i class="fa fa-plus" aria-hidden="true"></i> SUBMIT</button>
    </form>

2 个答案:

答案 0 :(得分:3)

您收到错误是因为您尝试在multer实际解析之前访问这些值。您正确地指出body-parser不适用于multipart-data,但在multipart-data表单类型中,multer可以解析file和其他字段form,这就是我们可以同时访问req.filereq.body的原因。

确保您在upload(req, res, function(err) { // req.body and req.file })

中访问它

此外,还存在与异步代码相关的问题。

<强>解决方案:

router.post('/new', middleware.isLoggedIn, function(req, res) {
    upload(req, res, function(err) {
       if (err) {
          req.flash('error', err.message);
          return res.redirect('/new');
       }

       var adObj = {
          owner: req.user,
          url: req.user.url,
          paymentType: req.body.paymentType,
          transactionId: '',
          banner: ''
       };

       if (adObj.paymentType === 'paid') {
         adObj.transactionId = req.body.transactionId;
       }

       adObj.banner = '/uploads/' + req.file.filename;

       var ad = new Ad(adObj);
       ad.save();

       req.flash('success', 'Successfully added new ad.');
       return res.redirect('/');
    });
});

答案 1 :(得分:0)

我遇到了同样的问题并花了几个小时解决它,需要确保您访问 req.body。上传下(req,res,err {