Back
+20 XP
Concept

Multipart Form Data Encoding from Scratch

File uploads use `multipart/form-data`. Each form field and binary file is separated by a unique random boundary string with specific MIME headers (`Content-Disposition`) 📦.

python
import uuid

boundary = "WebKitFormBoundary12345"
filename = "avatar.png"
file_bytes = b"\x89PNG\r\n\x1a\n"

# Construct multipart payload body:
body = (
    f"--{boundary}\r\n"
    f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
    f"Content-Type: image/png\r\n\r\n"
).encode("utf-8") + file_bytes + f"\r\n--{boundary}--\r\n".encode("utf-8")

print(f"Content-Type: multipart/form-data; boundary={boundary} 📦")
print(f"Total payload size: {len(body)} bytes ✅")

# 35. Multipart Form Data Encoding from Scratch File uploads use `multipart/form-data`. Each form field and binary file is separated by a unique random boundary string with specific MIME headers (`Content-Disposition`) 📦. ```python import uuid boundary = "WebKitFormBoundary12345" filename = "avatar.png" file_bytes = b"\x89PNG\r\n\x1a\n" # Construct multipart payload body: body = ( f"--{boundary}\r\n" f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n' f"Content-Type: image/png\r\n\r\n" ).encode("utf-8") + file_bytes + f"\r\n--{boundary}--\r\n".encode("utf-8") print(f"Content-Type: multipart/form-data; boundary={boundary} 📦") print(f"Total payload size: {len(body)} bytes ✅") ``` Understanding multipart boundaries demystifies how browsers upload gigabytes of files to cloud servers with streaming chunk efficiency! 📦 --- ### Question What character sequence marks the closing terminal boundary in a `multipart/form-data` payload? 🧠 - [ ] a. `--{boundary}--\r\n` (with two trailing hyphens) 📦 - [ ] b. `END_OF_FORM` - [ ] c. `<EOF>` - [ ] d. `--STOP--` --- ### Challenge Create a function `format_field(boundary, name, val)` that returns the multipart string chunk for a text field. Test with `boundary="B"`, `name="user"`, `val="ada"`. Print output. 🎯 <details> <summary>Solution</summary> ```python def format_field(boundary, name, val): return f"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{val}\r\n" res = format_field("B", "user", "ada") print(res.strip()) ``` </details>

Checkpoint

What character sequence marks the closing terminal boundary in a `multipart/form-data` payload? 🧠

Practice

Create a function `format_field(boundary, name, val)` that returns the multipart string chunk for a text field. Test with `boundary="B"`, `name="user"`, `val="ada"`. Print output. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks