multer req.body showing empty always

谁说我不能喝 提交于 2019-12-23 04:33:22

问题


I am learning nodejs and express, i was trying to do file upload below is my code

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

and below is my HTML

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

so my issue is console.log(req.body);// {"someParam": "someValue"} this is always showing empty object i google alot but didnt able to make it working

this is the output i am getting

[ { 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 } ]
{}

Thanks for help in advance


回答1:


The req.body will hold any text fields from your form if any are there, which in this case there aren't any. You don't specifically mention what you want to do with the file, but you can see that your file upload was successful when you log the req.files array. It has your file object there. You should be able to perform operations on that file either using the path or the buffer property of the object which contains a buffer of the entire file.




回答2:


In your app.js change this :

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

and try,



来源:https://stackoverflow.com/questions/51801180/multer-req-body-showing-empty-always

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!