Processing file uploads in Node.js requires parsing incoming HTTP multipart/form-data request streams, storing temporary chunks safely on disk or memory, and routing them to target storage directories.
flowchart TD
A["HTML Client Form (enctype='multipart/form-data')"] --> B["HTTP POST Stream Request"]
B --> C["Node.js Server Request Handler"]
C --> D["Stream Parser (e.g. Busboy / Formidable)"]
D --> E["Write Stream to /uploads/ destination"]
E --> F["Return HTTP 201 Upload Success Response"]
Low-level file upload handling demo (saving multipart binary stream data):
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
const UPLOAD_DIR = path.join(process.cwd(), 'uploads');
// Ensure uploads folder exists
if (!fs.existsSync(UPLOAD_DIR)) {
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.headers['content-type']?.includes('multipart/form-data')) {
const boundary = req.headers['content-type'].split('boundary=')[1];
const savePath = path.join(UPLOAD_DIR, `upload_${Date.now()}.bin`);
const fileWriteStream = fs.createWriteStream(savePath);
req.pipe(fileWriteStream);
req.on('end', () => {
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
status: 'success',
message: 'File upload stream received successfully',
savedFile: savePath
}));
});
req.on('error', (err) => {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
});
return;
}
// Serve Upload Form HTML
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<form action="/" method="POST" enctype="multipart/form-data">
<input type="file" name="attachment" required />
<button type="submit">Upload File</button>
</form>
`);
});
server.listen(4000, () => {
console.log('Upload Server running on http://localhost:4000');
});
.exe or shell scripts).What HTTP request header attribute must be present on an HTML <form> element to enable file upload binary transmission?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With