multer req.body始终显示为空

时间:2018-08-11 15:30:37

标签: node.js express multer

我正在学习nodejs并进行表达,我正尝试执行文件上传,以下是我的代码

const express = require('express');
const multer = require('multer');
const app = express();
const port = process.env.PORT||3000;
const path = require('path');
const fs= require('fs');
const xlsx = require('node-xlsx');
const bodyParser=require('body-parser')

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

const upload=multer({
  storage:storage
})


app.set('port',port);
app.set('view engine', 'ejs');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('./public'));

app.post('/uploadTest', upload.single('myImage'),function (req, res, next) {
setTimeout(function(){

  console.log(req.files);
  console.log(req.body);// {"someParam": "someValue"}
  res.send(req.body);


}, 3000);


  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

var server=app.listen(app.get('port'),(req,res)=>{
  console.log(`server started at port ${app.get('port')}`)
});

下面是我的HTML

<form action="/uploadTest" method="post" enctype="multipart/form-data">
    <input type="file" name="myImage"/>
    <input type="submit" value="Add File"/>
</form>

所以我的问题是console.log(req.body);// {"someParam": "someValue"},这总是在Google上显示很多空对象,但无法使其工作

这是我得到的输出

[ { fieldname: 'myImage',
    originalname: 'SampleXLSFile_19kb.xls',
    encoding: '7bit',
    mimetype: 'application/vnd.ms-excel',
    destination: './public/uploads',
    filename: 'myImage-1534000938255.xls',
    path: 'public\\uploads\\myImage-1534000938255.xls',
    size: 19456 } ]
{}

谢谢您的帮助

2 个答案:

答案 0 :(得分:0)

req.body将保留表单中的任何文本字段(如果存在),在这种情况下,该文本字段将不存在。您没有特别提到要使用该文件做什么,但是当您记录req.files数组时,可以看到文件上传成功。它在那里有您的文件对象。您应该能够使用包含整个文件缓冲区的对象的路径或属性buffer对该文件执行操作。

答案 1 :(得分:0)

在您的app.js中更改此内容:

const upload=multer({
  dest:'./public/uploads'
})

然后尝试