Skip to content

Instantly share code, notes, and snippets.

@Ndohjapan
Created May 16, 2021 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ndohjapan/c7c8fbcb380d27023181a6a0148b9361 to your computer and use it in GitHub Desktop.
Save Ndohjapan/c7c8fbcb380d27023181a6a0148b9361 to your computer and use it in GitHub Desktop.
// 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
const port = 3000
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)
fileFilter: (req, file, cb) => {
const validFileTypes = /jpg|jpeg|png/ // Create regex to match jpg and png
// Do the regex match to check if file extenxion match
const extname = validFileTypes.test(path.extname(file.originalname).toLowerCase())
if(extname === true){
// Return true and file is saved
return cb(null, true)
}else{
// Return error message if file extension does not match
cb("Error: Images Only!")
}
}
})
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
// The image will be found in the public folder
}
})
})
// Create the server and let it run on the port 3001
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment