I am trying to design a simple app in NodeJS that uploads a CSV file via an HTML form. Having carefully followed this tutorial on YouTube on how to upload files using NodeJS, I don't understand why my code isn't able to upload any file. I haven't gotten further than 6:53 mins in the youtube tutorial.
Find below my simple code:
const express = require('express');
const app = express();
const multer = require('multer');
const fileStorageEngine = multer.diskStorage({
destination: (req,file,cd)=> {
cd(null, './uploads')
},
filename: (req,file,cb)=>{
cb(null, Date.now() + '--' + file.originalname);
},
});
const upload = multer({storage: 'fileStorageEngine'});
app.get('/', (req,res)=> {
res.sendFile(__dirname +'/testDir/form.html' );
});
app.post('/uploads', upload.single('file'), (req, res)=> {
console.log(req.file);
res.send('Single File Upload Success!');
});
app.listen('3600', ()=> console.log('App is listening...'));
...and my HTML form code looks like this:
http://localhost:3600/
correctly displays
I am able to browse to whatever file I choose, and clicking on the submit button that gets me directed to:
According to the YouTube at 6:53 mins, the uploads folder should now contain the uploaded file, however, the folder is empty!
Also, the terminal displays
...suggesting that console.log(req.file);
no file was actually read in.
I also tried using postman and this is a screenshot of the result:
I have tried to re-watching the video and carefully followed the instructions but still haven't been able to resolve the issue.
Kindly help me understand why the upload isn't working and how to resolve this issue. Looking forward to your help.
You have set the storage
field as a string
instead of a multer.diskStorage
object.
Change it to: const upload = multer({storage: fileStorageEngine});
Also make sure that the key
value in Postman form-data is set to file
, because you are using upload.single('file')