@ts-stack/multiparty
Parse http requests with content-type multipart/form-data, also known as file uploads.
This is fork of multiparty from this state, writen in TypeScript.
Installation
This is a Node.js module available through the
npm registry. Installation is done using the
npm install command:
npm install @ts-stack/multiparty
Usage
Parse an incoming multipart/form-data request.
import http = require('http');
import util = require('util');
import { Form } from '@ts-stack/multiparty';
http.createServer((req, res) => {
if (req.url == '/upload' && req.method == 'POST') {
const form = new Form();
form.parse(req, (err, fields, files) => {
res.writeHead(200, { 'content-type': 'text/plain' });
res.write('received upload:\n\n');
res.end(util.inspect({ fields: fields, files: files }));
});
return;
}
res.writeHead(200, { 'content-type': 'text/html' });
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
API
Form
import { Form } from '@ts-stack/multiparty';
const form = new Form(options)
Creates a new form.
export class FormOptions {
encoding?: BufferEncoding;
maxFieldsSize?: number;
maxFields?: number;
maxFilesSize?: number;
autoFields?: boolean;
autoFiles?: boolean;
uploadDir?: string;
}
form.parse(request, cb?)
Parses an incoming node.js request containing form data.This will cause
form to emit events based off the incoming request.
import { Form } from '@ts-stack/multiparty';
let count = 0;
const form = new Form();
form.on('error', (err) => {
console.log('Error parsing form: ' + err.stack);
});
form.on('part', (part) => {
if (!part.filename) {
console.log('got field named ' + part.name);
part.resume();
}
if (part.filename) {
count++;
console.log('got file named ' + part.name);
part.resume();
}
part.on('error', (err) => {
});
});
form.on('close', () => {
console.log('Upload completed!');
res.setHeader('text/plain');
res.end('Received ' + count + ' files');
});
form.parse(req);
If cb is provided, autoFields and autoFiles are set to true and all
fields and files are collected and passed to the callback, removing the need to
listen to any events on form. This is for convenience when you want to read
everything, but be sure to write cleanup code, as this will write all uploaded
files to the disk, even ones you may not be interested in.
form.parse(req, (err, fields, files) => {
Object.keys(fields).forEach((name) => {
console.log(`got field named ${name}`);
});
Object.keys(files).forEach((name) => {
console.log(`got file named ${name}`);
});
console.log('Upload completed!');
res.setHeader('text/plain');
res.end(`Received ${files.length} files`);
});
fields is an object where the property names are field names and the values
are arrays of field values.
files is an object where the property names are field names and the values
are arrays of file objects.
form.bytesReceived
The amount of bytes received for this form so far.
form.bytesExpected
The expected number of bytes in this form.
Events
on(event: 'error', listener: (err: Error & { statusCode?: number }) => void): this;
on(event: 'part', listener: (part: PartEvent) => void): this;
on(event: 'aborted', listener: () => void): this;
on(event: 'progress', listener: (bytesReceived?: number, bytesExpected?: number) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'file', listener: (name?: string, file?: FormFile) => void): this;
on(event: 'field', listener: (name?: string, value?: string) => void): this;
Where PartEvent and FormFile is:
interface PartEvent extends ReadableStream {
headers: IncomingHttpHeaders;
name: string;
filename: string;
byteOffset: number;
byteCount: number;
on(event: 'error', listener: (err: Error & { statusCode?: number }) => void): this;
resume(): this;
}
interface FormFile {
fieldName: string;
originalFilename: string;
path: string;
headers: IncomingHttpHeaders;
size: number;
}
License
MIT