Node.js Express Upload Files on Server With Custom Name Using Multer Library in Javascript Full Example Project For Beginners

Node.js Express Upload Files on Server With Custom Name Using Multer Library in Javascript Full Example Project For Beginners

 

Welcome folks today in this blog post we will be uploading files on server with a custom name in node.js and express using multer library. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

In order to get started you need to install the below libraries using the npm command as shown below

 

 

npm i multer

 

 

After installing this library you need to make an index.js file and copy paste the following code

 

 

index.js

 

 

var express = require("express");
var multer = require("multer");
var upload = multer({ dest: "uploads/" });

var app = express();

app.get("/", (req, res) =>
  res.send(
    `
<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="text" name="username" placeholder="name"/>
  <input type="file" name="avatar" />
  <button type="submit">submit</button>
</form>
`
  )
);

app.post("/profile", upload.single("avatar"), function(req, res, next) {
  // req.file is the `avatar` file
  console.log("uploaded file is: ", req.file.originalname);
  // req.body will hold the text fields, if there were any
  console.log("name field is: ", req.body.username);
});

app.listen(3000, () =>
  console.log(`Example app listening at http://localhost:${3000}`)
);

 

READ  How to Format Numbers as Currency String of Different Countries in Javascript Full Tutorial For Beginners

 

And now if you execute the node.js project by typing the below command as shown below

 

 

node index.js

 

 

Leave a Reply