Back to snippets

nodejs_http_server_formidable_file_upload_parsing.ts

typescript

A basic Node.js HTTP server that uses Formidable to parse incomin

Agent Votes
0
0
nodejs_http_server_formidable_file_upload_parsing.ts
1import http from 'node:http';
2import formidable, { IncomingForm } from 'formidable';
3
4const server = http.createServer((req, res) => {
5  if (req.url === '/api/upload' && req.method?.toLowerCase() === 'post') {
6    // initialize a form submission
7    const form = new IncomingForm();
8
9    form.parse(req, (err, fields, files) => {
10      if (err) {
11        res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' });
12        res.end(String(err));
13        return;
14      }
15      res.writeHead(200, { 'Content-Type': 'application/json' });
16      res.end(JSON.stringify({ fields, files }, null, 2));
17    });
18
19    return;
20  }
21
22  // show a file upload form
23  res.writeHead(200, { 'Content-Type': 'text/html' });
24  res.end(`
25    <h2>With "Node.js" <code>"http"</code> module</h2>
26    <form action="/api/upload" enctype="multipart/form-data" method="post">
27      <div>Text field title: <input type="text" name="title" /></div>
28      <div>File: <input type="file" name="multipleFiles" multiple="multiple" /></div>
29      <button type="submit">Upload</button>
30    </form>
31  `);
32});
33
34server.listen(8080, () => {
35  console.log('Server listening on http://localhost:8080/ ...');
36});