Upload Files to Local public folder in NodeJs using Multer

Uploading files to a local public folder in Node.js using Multer involves a few steps. This article helps you set it up.

Install Multer

First, you need to install Multer, which is a Node.js middleware for handling multipart/form-data, primarily used for uploading files.

npm install multer

Set Up Your Server

  • Include express and multer in your server file.
  • Use express.static(‘public’) to serve files from the public directory.
const express = require('express');
const multer = require('multer');
const app = express();

app.use(express.static('public'));

Configure Multer Storage

  • Define storage using multer.diskStorage.
  • Set the destination to the desired location (public/uploads in this case).
  • Set the filename function to create unique filenames (combines field name and timestamp).
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});

const upload = multer({ storage: storage });

Create an Upload Route

  • Create a route (e.g., /upload) to handle file upload requests with POST method.
  • Use upload.single(‘file’) middleware to handle single file uploads with the field name file.
  • In the route handler function, you can access uploaded file details in req.file.
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully.');
});

Create a Form to Submit Files

  • On the front end, create a form that allows users to select and submit files.
  • Create an HTML form with action=”/upload”, method=”post”, and enctype=”multipart/form-data”.
  • Include a file input element with name=”file” and a submit button.
<form action="/upload" method="post" enctype="multipart/form-data">  
<input type="file" name="file" />
<input type="submit" value="Upload File" />
</form>

Start the Server

Finally, start your server.

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

This setup will allow you to upload files to the public/uploads directory on your server. Make sure the public/uploads directory exists, or Multer will throw an error.

Example: Frontend (index.html): It is the front end user interface.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
          "width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h1>File Upload Form</h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <label for="file">Select File:</label>
        <input type="file" name="file" id="file">
        <br>
        <button type="submit">Upload File</button>
    </form>
</body>
</html>

Backend (app.js):

JavaScript
const express = require("express");
const multer = require("multer");
const path = require("path");
const app = express();

app.use(express.static("public"));

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + "-" + Date.now());
  },
});

const upload = multer({ storage: storage });

// Serve index.html at the root URL
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.post("/upload", upload.single("file"), (req, res) => {
  res.send("File uploaded successfully.");
});

const PORT =  3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Output:

Run the App

  • Make sure you have Node.js and npm installed.
  • Initialize a new Node.js project (if you haven’t already):
npm init -y
  • Install the necessary dependencies:
npm install express multer
  • Create the project structure as shown .
  • Save the backend code to app.js and the frontend code to public/index.html.
  • Create the public/uploads directory:
mkdir -p public/uploads
  • Start the server:
node app.js

Open your web browser and navigate to http://localhost:3000. You should see the file upload form. Select a file and click “Upload File” to test the upload functionality.

By following these steps, you should have a working file upload feature in your Node.js application using Multer. The uploaded files will be stored in the public/uploads directory.