Java, .NET, PHP, PYTHON, ANGULAR, .NET, ML, Data Scince, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

File Uploading Code using Node and Express Js

Step1st:-   Create Front End  File using HTML or ,ANGULAR,

Step2nd:-

<html>
   <head>
      <title>File Uploading Form</title>
   </head>

   <body>
      <h3>File Upload:</h3>
      Select a file to upload: <br />
     
      <form action = "http://localhost:3000/uploadfile" method = "POST"
         enctype = "multipart/form-data">
         <input type="file" name="myFile" size="50" />
         <br />
         <input type = "submit" value = "Upload File" />
      </form>
     
   </body>
</html>


Step 3rd:-
const express = require('express')
const bodyParser= require('body-parser')
const multer = require('multer');
const app = express()
 app.use(bodyParser.urlencoded({extended: true}))

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage })


//ROUTES WILL GO HERE
app.get('/', function(req, res) {
    res.json({ message: 'WELCOME' }); 
});
app.post('/uploadfile', upload.single('myFile'), (req, res, next) => {
  const file = req.file
  if (!file) {
    const error = new Error('Please upload a file')
    error.httpStatusCode = 400
    return next(error)
  }
    res.send(file)
 
})
app.listen(3000, () => console.log('Server started on port 3000'));



                                            

Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post