Skip to content

Instantly share code, notes, and snippets.

app.post("/upload", (req, res) => {
// This is the response sent to the user in the browser once the file recieved
res.send("Hello World")
})
// Run the server form the terminal
$ node app.js
// Server is running on port 3000
npm install multer express
USER@User MINGW64 ~/Desktop/upload
$ npm init -y
// Include the express module into the poject for creating the server
const express = require("express")
// Include the multer module into the project for accepting files
const multer = require("multer")
// We will set the object received from the express() function to a variable "app"
const app = express()
// Set a port on which the server will run on
app.post("/upload", (req, res) => {
// This is the response sent to the user in the browser once the file recieved
upload(req, res, (err) => {
if(err){
res.send(err)
// This will display the error message to the user
}
else{
res.send("File Uploaded Successfully")
// This shows the file has beem successfully uploaded
const upload = multer({
storage: multer.diskstorage({
destination: "/upload/images", // Storage location
filename: (req, res, (cb) => {
cb(null, Date.now() + path.extname(file.originalname)) // return a unique file name for every file
})
}),
limits: {fileSize: 20000000, // This limits file size to 2 million bytes(2mb)
app.post("/upload", (req, res) => {
// This is the response sent to the user in the browser once the file recieved
res.send("Hello World")
})
app.use(express.static("public"))
// Server will render the html file in the public folder which is index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<div class="container">