0
0
Expressframework~30 mins

File type validation in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
File type validation
📖 Scenario: You are building a simple Express server that accepts file uploads. To keep the server safe and organized, you want to allow only image files of type PNG and JPEG.
🎯 Goal: Create an Express server that validates uploaded files to accept only PNG and JPEG images.
📋 What You'll Learn
Create an Express app with a POST route /upload to accept file uploads.
Use the multer middleware to handle file uploads.
Create a file filter function that only accepts files with MIME types image/png and image/jpeg.
Send a response indicating success or failure based on file type validation.
💡 Why This Matters
🌍 Real World
File type validation is important to prevent users from uploading harmful or unwanted files to your server. This keeps your app secure and organized.
💼 Career
Backend developers often need to handle file uploads safely. Knowing how to validate file types with Express and multer is a common task in web development jobs.
Progress0 / 4 steps
1
Set up Express app and multer
Create an Express app by requiring express and multer. Then create an instance of Express called app and set up multer with const upload = multer().
Express
Need a hint?

Use require('express') and require('multer') to import the modules. Then call express() to create the app and multer() to create the upload handler.

2
Create file filter function
Create a function called fileFilter that takes req, file, and cb as parameters. Inside, check if file.mimetype is either image/png or image/jpeg. If yes, call cb(null, true), else call cb(null, false).
Express
Need a hint?

The fileFilter function controls which files multer accepts. Use file.mimetype to check the file type and call cb accordingly.

3
Add POST route with upload middleware
Add a POST route /upload to the Express app. Use upload.single('file') as middleware to handle a single file upload with the field name file. In the route handler, send a JSON response with { success: true } if req.file exists, else { success: false, message: 'Invalid file type' }.
Express
Need a hint?

Use app.post to create the route. Use upload.single('file') to handle the file upload. Check req.file to see if the file passed the filter.

4
Start the Express server
Add code to start the Express server on port 3000 using app.listen. Log the message 'Server running on port 3000' when the server starts.
Express
Need a hint?

Use app.listen(3000, () => { ... }) to start the server and log a message.