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.
<!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):
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:
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.
Contact Us