node.jsexpressmulter-gridfs-storage

Why am I NOT able to upload files with the following NodeJS code?


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: enter image description here

http://localhost:3600/ correctly displays

enter image description here

I am able to browse to whatever file I choose, and clicking on the submit button that gets me directed to:

enter image description here

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

enter image description here

...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:

enter image description here 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.


Solution

  • 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')