i am learning nodejs and trying to upload a image file without page reload, i'm using this code below but it does not work. Req.body is empty. Can anyone help me ?
in my ejs file:
`````````````````
<body>
<form action="/" method='post' enctype="multipart/form-data" id='form-data'>
<input type="file" name='file' id='file' class='file'>
</form>
<script>
$(document).on('change', '#file', function () {
var property = document.getElementById('file').files[0];
var form_data = new FormData();
form_data.append('file', property);
$.post({
url: '/',
type: 'post',
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function (data) {
console.log(data);
}
})
})
</script>
</body>
`````````````````
This is server.js:
const express = require('express');
const app = express();
const path = require('path');
app.set('view engine', 'ejs');
app.set('views' , __dirname);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true }));
app.post('/', (req,res) =>{
console.log(req.body)
})
app.get("/", (req,res) =>{
res.render('main');
})
app.listen(3000);
CodePudding user response:
The easiest way I know to achieve what your aiming to do is with multer
Express doesn't easily handle files on its own, so by bringing multer in as a middleware you easily upload files. take a look at line 5 and see "dest", change that to wherever you want the files to be uploaded to
On line 12 I have added the middleware to the post route, the reason I have passed in 'file' is that the form data key for the file is 'file'
On line 13 I have change console.log from req.body to req.file as you can access the file information from there with multer
const express = require('express');
const app = express();
const path = require('path');
const multer = require('multer')
const upload = multer({ dest: './uploads/' })
app.set('view engine', 'ejs');
app.set('views' , __dirname);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true }));
app.post('/', upload.single('file'), (req,res) =>{
console.log(req.files)
})
app.get("/", (req,res) =>{
res.render('main');
})
app.listen(3000);
To install multer check out the link I have added or simply type:
npm install multer
Cheers, Daniel