|
| 1 | +// warning: forcing file into a Buffer elminates the benefits of using streams and may cause memory overflow |
| 2 | +import http from 'node:http'; |
| 3 | +import { Buffer } from 'node:buffer' |
| 4 | +import { Writable } from 'node:stream'; |
| 5 | +import formidable from '../src/index.js'; |
| 6 | + |
| 7 | + |
| 8 | +const server = http.createServer((req, res) => { |
| 9 | + if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') { |
| 10 | + // parse a file upload |
| 11 | + const endBuffers = {}; |
| 12 | + const form = formidable({ |
| 13 | + fileWriteStreamHandler: (file) => { |
| 14 | + const chunks = []; |
| 15 | + |
| 16 | + const writable = new Writable({ |
| 17 | + write (chunk, enc, next) { |
| 18 | + chunks.push(chunk); |
| 19 | + next(); |
| 20 | + }, |
| 21 | + destroy() { |
| 22 | + endBuffers = {}; |
| 23 | + }, |
| 24 | + final(cb) { |
| 25 | + const buffer = Buffer.concat(chunks); |
| 26 | + // if filename option is not provided file.newFilename will be a random string |
| 27 | + endBuffers[file.newFilename] = buffer; |
| 28 | + cb(); |
| 29 | + }, |
| 30 | + }) |
| 31 | + return writable; |
| 32 | + }, |
| 33 | + }); |
| 34 | + |
| 35 | + form.parse(req, (err, fields, files) => { |
| 36 | + // available here endBuffers |
| 37 | + if (err) { |
| 38 | + console.error(err); |
| 39 | + res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' }); |
| 40 | + res.end(String(err)); |
| 41 | + return; |
| 42 | + } |
| 43 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 44 | + res.end(JSON.stringify({ fields, files }, null, 2)); |
| 45 | + |
| 46 | + Object.entries(endBuffers).map(([key, value]) => { |
| 47 | + console.log(key); |
| 48 | + console.log(value.toString("utf8")); |
| 49 | + }); |
| 50 | + }); |
| 51 | + |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + // show a file upload form |
| 56 | + res.writeHead(200, { 'Content-Type': 'text/html' }); |
| 57 | + res.end(` |
| 58 | + <h2>With Node.js <code>"http"</code> module</h2> |
| 59 | + <form action="/api/upload" enctype="multipart/form-data" method="post"> |
| 60 | + <div>Text field title: <input type="text" name="title"></div> |
| 61 | + <div>File: <input type="file" name="myfile"></div> |
| 62 | + <button>Upload</button> |
| 63 | + </form> |
| 64 | + `); |
| 65 | +}); |
| 66 | + |
| 67 | +server.listen(3000, () => { |
| 68 | + console.log('Server listening on http://localhost:3000 ...'); |
| 69 | +}); |
0 commit comments