|
| 1 | +# FormData |
| 2 | + |
| 3 | +The `FormData` class is used to construct form data (`multipart/form-data`) for uploading text fields or file data in network requests. |
| 4 | +Its behavior is basically consistent with the **Fetch API FormData** in browsers, but in **Scripting app**, it is extended to support the `Data` type (native binary objects), making file or image uploads more convenient. |
| 5 | + |
| 6 | +You can use a `FormData` object directly as the `body` parameter of a `fetch()` request. The system will automatically generate a `multipart/form-data` request body with the correct boundary. |
| 7 | + |
| 8 | +--- |
| 9 | + |
| 10 | +## Definition |
| 11 | + |
| 12 | +```ts |
| 13 | +class FormData { |
| 14 | + append(name: string, value: string): void |
| 15 | + append(name: string, value: Data, mimeType: string, filename?: string): void |
| 16 | + get(name: string): string | Data | null |
| 17 | + getAll(name: string): any[] |
| 18 | + has(name: string): boolean |
| 19 | + delete(name: string): void |
| 20 | + set(name: string, value: string): void |
| 21 | + set(name: string, value: Data, filename?: string): void |
| 22 | + forEach(callback: (value: any, name: string, parent: FormData) => void): void |
| 23 | + entries(): [string, any][] |
| 24 | + toJson(): Record<string, any> |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +--- |
| 29 | + |
| 30 | +## Main Uses |
| 31 | + |
| 32 | +* Construct form requests containing both text and file data |
| 33 | +* Use for file upload APIs (e.g., images, audio, documents) |
| 34 | +* Replace JSON structures when uploading binary or form data |
| 35 | + |
| 36 | +--- |
| 37 | + |
| 38 | +## Method Description |
| 39 | + |
| 40 | +### `append(name: string, value: string): void` |
| 41 | + |
| 42 | +### `append(name: string, value: Data, mimeType: string, filename?: string): void` |
| 43 | + |
| 44 | +Add a field to the form. |
| 45 | +Can be used to add text fields or file data. |
| 46 | + |
| 47 | +#### Parameter Description |
| 48 | + |
| 49 | +| Parameter | Type | Description | |
| 50 | +| -------------- | ----------------- | ------------------------------------------------------------ | |
| 51 | +| **name** | `string` | Field name. | |
| 52 | +| **value** | `string` | `Data` | Field value, can be a string or `Data` object (binary file). | |
| 53 | +| **mimeType** | `string` | File MIME type (e.g. `"image/png"`). Required only when passing `Data`. | |
| 54 | +| **filename** | `string` (optional) | File name, used only when uploading files. | |
| 55 | + |
| 56 | +#### Example |
| 57 | + |
| 58 | +```tsx |
| 59 | +const form = new FormData() |
| 60 | +form.append("username", "Tom") |
| 61 | +form.append("file", Data.fromFile("/path/to/image.png"), "image/png", "avatar.png") |
| 62 | +``` |
| 63 | + |
| 64 | +--- |
| 65 | + |
| 66 | +### `set(name: string, value: string): void` |
| 67 | + |
| 68 | +### `set(name: string, value: Data, filename?: string): void` |
| 69 | + |
| 70 | +Set the value of a field. |
| 71 | +If the field already exists, it will be overwritten. |
| 72 | +Difference from `append()`: `set()` keeps only one value, while `append()` allows multiple values for the same field name. |
| 73 | + |
| 74 | +#### Example |
| 75 | + |
| 76 | +```tsx |
| 77 | +const form = new FormData() |
| 78 | +form.set("message", "Hello world") |
| 79 | +form.set("file", Data.fromFile("/path/to/file.txt"), "text/plain", "note.txt") |
| 80 | +``` |
| 81 | + |
| 82 | +--- |
| 83 | + |
| 84 | +### `get(name: string): string | Data | null` |
| 85 | + |
| 86 | +Get the value of a specified field. |
| 87 | +If the field does not exist, returns `null`. |
| 88 | + |
| 89 | +#### Example |
| 90 | + |
| 91 | +```tsx |
| 92 | +const form = new FormData() |
| 93 | +form.append("title", "My Post") |
| 94 | +console.log(form.get("title")) // Output: "My Post" |
| 95 | +``` |
| 96 | + |
| 97 | +--- |
| 98 | + |
| 99 | +### `getAll(name: string): any[]` |
| 100 | + |
| 101 | +Get all values of fields with the same name (if `append()` was used multiple times). |
| 102 | + |
| 103 | +#### Example |
| 104 | + |
| 105 | +```tsx |
| 106 | +const form = new FormData() |
| 107 | +form.append("tag", "swift") |
| 108 | +form.append("tag", "ios") |
| 109 | +form.append("tag", "scripting") |
| 110 | + |
| 111 | +console.log(form.getAll("tag")) // ["swift", "ios", "scripting"] |
| 112 | +``` |
| 113 | + |
| 114 | +--- |
| 115 | + |
| 116 | +### `has(name: string): boolean` |
| 117 | + |
| 118 | +Check whether a field with the specified name exists in the form. |
| 119 | + |
| 120 | +#### Example |
| 121 | + |
| 122 | +```tsx |
| 123 | +const form = new FormData() |
| 124 | +form.append("username", "Tom") |
| 125 | + |
| 126 | +console.log(form.has("username")) // true |
| 127 | +console.log(form.has("password")) // false |
| 128 | +``` |
| 129 | + |
| 130 | +--- |
| 131 | + |
| 132 | +### `delete(name: string): void` |
| 133 | + |
| 134 | +Delete a field and all its values. |
| 135 | + |
| 136 | +#### Example |
| 137 | + |
| 138 | +```tsx |
| 139 | +const form = new FormData() |
| 140 | +form.append("title", "Hello") |
| 141 | +form.append("file", Data.fromFile("/path/to/file.txt"), "text/plain") |
| 142 | + |
| 143 | +form.delete("file") |
| 144 | +``` |
| 145 | + |
| 146 | +--- |
| 147 | + |
| 148 | +### `forEach(callback: (value: any, name: string, parent: FormData) => void): void` |
| 149 | + |
| 150 | +Iterate over all form fields and execute a callback function. |
| 151 | + |
| 152 | +#### Example |
| 153 | + |
| 154 | +```tsx |
| 155 | +const form = new FormData() |
| 156 | +form.append("user", "Tom") |
| 157 | +form.append("age", "25") |
| 158 | + |
| 159 | +form.forEach((value, name) => { |
| 160 | + console.log(`${name}: ${value}`) |
| 161 | +}) |
| 162 | +``` |
| 163 | + |
| 164 | +--- |
| 165 | + |
| 166 | +### `entries(): [string, any][]` |
| 167 | + |
| 168 | +Return an array of key-value pairs `[name, value]`. |
| 169 | + |
| 170 | +#### Example |
| 171 | + |
| 172 | +```tsx |
| 173 | +const form = new FormData() |
| 174 | +form.append("username", "Tom") |
| 175 | +form.append("age", "25") |
| 176 | +console.log(form.entries()) |
| 177 | +// [["username", "Tom"], ["age", "25"]] |
| 178 | +``` |
| 179 | + |
| 180 | +--- |
| 181 | + |
| 182 | +### `toJson(): Record<string, any>` |
| 183 | + |
| 184 | +Convert form data to a regular JavaScript object for debugging or logging. |
| 185 | +⚠️ Note: If the form contains files (`Data` type), this method will not output binary content, but show placeholder info instead. |
| 186 | + |
| 187 | +#### Example |
| 188 | + |
| 189 | +```tsx |
| 190 | +const form = new FormData() |
| 191 | +form.append("name", "Tom") |
| 192 | +form.append("photo", Data.fromFile("/path/to/avatar.png"), "image/png", "avatar.png") |
| 193 | + |
| 194 | +console.log(form.toJson()) |
| 195 | +// { name: "Tom", photo: "[Data: image/png]" } |
| 196 | +``` |
| 197 | + |
| 198 | +--- |
| 199 | + |
| 200 | +## Usage Examples |
| 201 | + |
| 202 | +### Example 1: Upload a file |
| 203 | + |
| 204 | +```tsx |
| 205 | +const form = new FormData() |
| 206 | +form.append("file", Data.fromFile("/path/to/image.png"), "image/png", "avatar.png") |
| 207 | +form.append("userId", "1234") |
| 208 | + |
| 209 | +const response = await fetch("https://api.example.com/upload", { |
| 210 | + method: "POST", |
| 211 | + body: form, |
| 212 | +}) |
| 213 | + |
| 214 | +console.log(await response.json()) |
| 215 | +``` |
| 216 | + |
| 217 | +--- |
| 218 | + |
| 219 | +### Example 2: Upload multiple files |
| 220 | + |
| 221 | +```tsx |
| 222 | +const form = new FormData() |
| 223 | +form.append("files", Data.fromFile("/path/to/photo1.jpg"), "image/jpeg", "photo1.jpg") |
| 224 | +form.append("files", Data.fromFile("/path/to/photo2.jpg"), "image/jpeg", "photo2.jpg") |
| 225 | + |
| 226 | +await fetch("https://api.example.com/multi-upload", { |
| 227 | + method: "POST", |
| 228 | + body: form, |
| 229 | +}) |
| 230 | +``` |
| 231 | + |
| 232 | +--- |
| 233 | + |
| 234 | +### Example 3: Construct a mixed text and file request |
| 235 | + |
| 236 | +```tsx |
| 237 | +const form = new FormData() |
| 238 | +form.append("title", "Travel Memories") |
| 239 | +form.append("description", "A collection of my travel photos.") |
| 240 | +form.append("cover", Data.fromFile("/path/to/cover.png"), "image/png", "cover.png") |
| 241 | + |
| 242 | +const response = await fetch("https://example.com/uploadPost", { |
| 243 | + method: "POST", |
| 244 | + body: form, |
| 245 | +}) |
| 246 | + |
| 247 | +console.log(await response.text()) |
| 248 | +``` |
| 249 | + |
| 250 | +--- |
| 251 | + |
| 252 | +### Example 4: Iterate and debug form content |
| 253 | + |
| 254 | +```tsx |
| 255 | +const form = new FormData() |
| 256 | +form.append("name", "Alice") |
| 257 | +form.append("file", Data.fromFile("/path/to/file.txt"), "text/plain", "file.txt") |
| 258 | + |
| 259 | +form.forEach((value, name) => { |
| 260 | + console.log(`${name}:`, value instanceof Data ? "Binary Data" : value) |
| 261 | +}) |
| 262 | +``` |
| 263 | + |
| 264 | +--- |
| 265 | + |
| 266 | +## Relationship with Other Classes |
| 267 | + |
| 268 | +| Class Name | Description | |
| 269 | +| -------------- | ---------------------------------------------------------------------------- | |
| 270 | +| **`fetch()`** | Can directly use a `FormData` instance as the request body. Automatically sets `multipart/form-data` headers. | |
| 271 | +| **`Data`** | Represents binary content such as files or images, passed as field values in `FormData`. | |
| 272 | +| **`Request`** | Can set a `FormData` instance in `RequestInit.body`. | |
| 273 | +| **`Response`** | Can parse response to `FormData` using `response.formData()`. | |
| 274 | + |
| 275 | +--- |
| 276 | + |
| 277 | +## Notes |
| 278 | + |
| 279 | +* **Automatic Content-Type setting**: When using `FormData`, `fetch()` automatically sets the correct `Content-Type` (with boundary). Do not set it manually. |
| 280 | +* **Duplicate field names**: Supports multiple values for the same name using `append()`. |
| 281 | +* **File upload**: You must provide a MIME type when uploading files, otherwise it may default to `application/octet-stream`. |
| 282 | +* **JSON conversion limitation**: `toJson()` is for debugging only, not suitable for real data transmission. |
| 283 | + |
| 284 | +--- |
| 285 | + |
| 286 | +## Summary |
| 287 | + |
| 288 | +`FormData` is the **core class in the Scripting network request system for constructing multipart/form-data requests**, featuring: |
| 289 | + |
| 290 | +* Supports mixed upload of text and files |
| 291 | +* Seamless integration with `fetch()` |
| 292 | +* Supports `Data` type for file transmission |
| 293 | +* Provides convenient helper methods like `forEach()`, `entries()`, `toJson()`, etc. |
| 294 | +* Fully compatible with the Web standard FormData behavior |
0 commit comments