The server's job is to receive the binary stream, validate it, and save it. Because Node.js is single-threaded, we use middleware to handle multipart/form-data. The industry standard is Multer.
Never trust the file extension provided by the user. Check it against a whitelist.
function fileFilter (req, file, cb) pdf/;
// Check extension
const extName = allowedTypes.test(path.extname(file.originalname).toLowerCase());
// Check mime type
const mimeType = allowedTypes.test(file.mimetype);
if (extName && mimeType)
return cb(null, true);
else
cb(new Error('Error: File type not allowed!'));
This is the simplest method. The browser handles everything, and the user is redirected to a new page upon completion.
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="userFile" />
<button type="submit">Upload</button>
</form>
Critical Detail: You must include enctype="multipart/form-data". Without this, the browser will send the filename as text string, not the actual binary file content.