-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathFormData.ts
More file actions
62 lines (55 loc) · 2.23 KB
/
FormData.ts
File metadata and controls
62 lines (55 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import path from 'node:path';
import _FormData from 'form-data';
// eslint-disable-next-line
const NON_ASCII_RE = /[^\x00-\x7F]/i;
export class FormData extends _FormData {
_getContentDisposition(value: any, options: any): string | undefined {
// support non-ascii filename
// https://github.com/form-data/form-data/pull/571
let filename;
let contentDisposition;
if (typeof options.filepath === 'string') {
// custom filepath for relative paths
filename = path.normalize(options.filepath).replace(/\\/g, '/');
} else if (options.filename || value.name || value.path) {
// custom filename take precedence
// formidable and the browser add a name property
// fs- and request- streams have path property
filename = path.basename(options.filename || value.name || value.path);
} else if (value.readable && value.hasOwnProperty('httpVersion')) {
// or try http response
filename = path.basename(value.client._httpMessage.path || '');
}
if (filename) {
// https://datatracker.ietf.org/doc/html/rfc6266#section-4.1
// support non-ascii filename
contentDisposition = 'filename="' + filename + '"';
if (NON_ASCII_RE.test(filename)) {
contentDisposition += "; filename*=UTF-8''" + encodeURIComponent(filename);
}
}
return contentDisposition;
}
/**
* Convert FormData to Buffer by consuming the CombinedStream.
* This is needed for Bun compatibility since Bun's undici
* doesn't support Node.js Stream objects as request body.
*
* Note: CombinedStream (which form-data extends) requires
* resume() to start data flow, unlike standard Readable streams.
*/
async toBuffer(): Promise<Buffer> {
return new Promise<Buffer>((resolve, reject) => {
const chunks: Buffer[] = [];
this.on('data', (chunk: Buffer | string) => {
// CombinedStream emits boundary/header strings alongside Buffer data
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
});
this.on('end', () => resolve(Buffer.concat(chunks)));
this.on('error', reject);
// CombinedStream pauses by default and only starts
// flowing when piped or explicitly resumed
this.resume();
});
}
}