FormData
The FormData class is used to construct form data (multipart/form-data) for uploading text fields or file data in network requests.
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.
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.
Definition
1class FormData {
2 append(name: string, value: string): void
3 append(name: string, value: Data, mimeType: string, filename?: string): void
4 get(name: string): string | Data | null
5 getAll(name: string): any[]
6 has(name: string): boolean
7 delete(name: string): void
8 set(name: string, value: string): void
9 set(name: string, value: Data, filename?: string): void
10 forEach(callback: (value: any, name: string, parent: FormData) => void): void
11 entries(): [string, any][]
12 toJson(): Record<string, any>
13}
Main Uses
- Construct form requests containing both text and file data
- Use for file upload APIs (e.g., images, audio, documents)
- Replace JSON structures when uploading binary or form data
Method Description
append(name: string, value: string): void
append(name: string, value: Data, mimeType: string, filename?: string): void
Add a field to the form.
Can be used to add text fields or file data.
Parameter Description
| Parameter |
Type |
Description |
| name |
string |
Field name. |
| value |
string |
Data |
| mimeType |
string |
File MIME type (e.g. "image/png"). Required only when passing Data. |
| filename |
string (optional) |
File name, used only when uploading files. |
Example
1const form = new FormData()
2form.append("username", "Tom")
3form.append("file", Data.fromFile("/path/to/image.png"), "image/png", "avatar.png")
set(name: string, value: string): void
set(name: string, value: Data, filename?: string): void
Set the value of a field.
If the field already exists, it will be overwritten.
Difference from append(): set() keeps only one value, while append() allows multiple values for the same field name.
Example
1const form = new FormData()
2form.set("message", "Hello world")
3form.set("file", Data.fromFile("/path/to/file.txt"), "text/plain", "note.txt")
get(name: string): string | Data | null
Get the value of a specified field.
If the field does not exist, returns null.
Example
1const form = new FormData()
2form.append("title", "My Post")
3console.log(form.get("title")) // Output: "My Post"
getAll(name: string): any[]
Get all values of fields with the same name (if append() was used multiple times).
Example
1const form = new FormData()
2form.append("tag", "swift")
3form.append("tag", "ios")
4form.append("tag", "scripting")
5
6console.log(form.getAll("tag")) // ["swift", "ios", "scripting"]
has(name: string): boolean
Check whether a field with the specified name exists in the form.
Example
1const form = new FormData()
2form.append("username", "Tom")
3
4console.log(form.has("username")) // true
5console.log(form.has("password")) // false
delete(name: string): void
Delete a field and all its values.
Example
1const form = new FormData()
2form.append("title", "Hello")
3form.append("file", Data.fromFile("/path/to/file.txt"), "text/plain")
4
5form.delete("file")
forEach(callback: (value: any, name: string, parent: FormData) => void): void
Iterate over all form fields and execute a callback function.
Example
1const form = new FormData()
2form.append("user", "Tom")
3form.append("age", "25")
4
5form.forEach((value, name) => {
6 console.log(`${name}: ${value}`)
7})
entries(): [string, any][]
Return an array of key-value pairs [name, value].
Example
1const form = new FormData()
2form.append("username", "Tom")
3form.append("age", "25")
4console.log(form.entries())
5// [["username", "Tom"], ["age", "25"]]
toJson(): Record<string, any>
Convert form data to a regular JavaScript object for debugging or logging.
⚠️ Note: If the form contains files (Data type), this method will not output binary content, but show placeholder info instead.
Example
1const form = new FormData()
2form.append("name", "Tom")
3form.append("photo", Data.fromFile("/path/to/avatar.png"), "image/png", "avatar.png")
4
5console.log(form.toJson())
6// { name: "Tom", photo: "[Data: image/png]" }
Usage Examples
Example 1: Upload a file
1const form = new FormData()
2form.append("file", Data.fromFile("/path/to/image.png"), "image/png", "avatar.png")
3form.append("userId", "1234")
4
5const response = await fetch("https://api.example.com/upload", {
6 method: "POST",
7 body: form,
8})
9
10console.log(await response.json())
Example 2: Upload multiple files
1const form = new FormData()
2form.append("files", Data.fromFile("/path/to/photo1.jpg"), "image/jpeg", "photo1.jpg")
3form.append("files", Data.fromFile("/path/to/photo2.jpg"), "image/jpeg", "photo2.jpg")
4
5await fetch("https://api.example.com/multi-upload", {
6 method: "POST",
7 body: form,
8})
Example 3: Construct a mixed text and file request
1const form = new FormData()
2form.append("title", "Travel Memories")
3form.append("description", "A collection of my travel photos.")
4form.append("cover", Data.fromFile("/path/to/cover.png"), "image/png", "cover.png")
5
6const response = await fetch("https://example.com/uploadPost", {
7 method: "POST",
8 body: form,
9})
10
11console.log(await response.text())
Example 4: Iterate and debug form content
1const form = new FormData()
2form.append("name", "Alice")
3form.append("file", Data.fromFile("/path/to/file.txt"), "text/plain", "file.txt")
4
5form.forEach((value, name) => {
6 console.log(`${name}:`, value instanceof Data ? "Binary Data" : value)
7})
Relationship with Other Classes
| Class Name |
Description |
fetch() |
Can directly use a FormData instance as the request body. Automatically sets multipart/form-data headers. |
Data |
Represents binary content such as files or images, passed as field values in FormData. |
Request |
Can set a FormData instance in RequestInit.body. |
Response |
Can parse response to FormData using response.formData(). |
Notes
- Automatic Content-Type setting: When using
FormData, fetch() automatically sets the correct Content-Type (with boundary). Do not set it manually.
- Duplicate field names: Supports multiple values for the same name using
append().
- File upload: You must provide a MIME type when uploading files, otherwise it may default to
application/octet-stream.
- JSON conversion limitation:
toJson() is for debugging only, not suitable for real data transmission.
Summary
FormData is the core class in the Scripting network request system for constructing multipart/form-data requests, featuring:
- Supports mixed upload of text and files
- Seamless integration with
fetch()
- Supports
Data type for file transmission
- Provides convenient helper methods like
forEach(), entries(), toJson(), etc.
- Fully compatible with the Web standard FormData behavior