Reputation: 658
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
Upvotes: 1
Views: 2045
Reputation: 135
In your app.js change this :
const upload=multer({
dest:'./public/uploads'
})
and try,
Upvotes: 0
Reputation: 1533
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.
Upvotes: 1