"""Offline Android file upload (Base64 form & multipart/form-data) loopback verifier (Ch 91: tutorial-upload-file)."""
from __future__ import annotations
import base64
import email.parser
import email.policy
import hashlib
import http.client
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"
MOCK_AVATAR = b"\x89PNG\r\n\x1a\nAVATAR_BYTES_0123456789"
class UploadServerHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format: str, *args) -> None:
return
def _json_reply(self, code: int, payload: dict) -> None:
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length)
ctype = self.headers.get("Content-Type", "")
if self.path == "/postIcon":
form = urllib.parse.parse_qs(raw.decode("utf-8"))
b64 = form.get("img", [""])[0]
decoded = base64.b64decode(b64)
self._json_reply(200, {
"decoded_len": len(decoded),
"sha256": hashlib.sha256(decoded).hexdigest(),
})
elif self.path == "/uploadMultipart":
header_block = f"Content-Type: {ctype}\r\nMIME-Version: 1.0\r\n\r\n".encode("ascii")
msg = email.parser.BytesParser(policy=email.policy.default).parsebytes(header_block + raw)
fields = {}
files = {}
for part in msg.iter_parts():
name = part.get_param("name", header="content-disposition")
filename = part.get_filename()
payload = part.get_payload(decode=True)
if filename:
files[name] = {
"filename": filename,
"content_type": part.get_content_type(),
"len": len(payload),
"sha256": hashlib.sha256(payload).hexdigest(),
}
else:
fields[name] = payload.decode("utf-8")
self._json_reply(200, {"fields": fields, "files": files})
elif self.path == "/postXml":
self._json_reply(200, {"content_type": ctype, "xml_body": raw.decode("utf-8")})
else:
self._json_reply(404, {"error": "unknown_route"})
def build_multipart(boundary: str, fields: dict[str, str], files: list[tuple[str, str, str, bytes]]) -> bytes:
"""Build RFC 7578 multipart/form-data payload using proper CRLF (\\r\\n)."""
chunks: list[bytes] = []
for k, v in fields.items():
chunks.append(f"--{boundary}\r\n".encode("ascii"))
chunks.append(f'Content-Disposition: form-data; name="{k}"\r\n\r\n'.encode("utf-8"))
chunks.append(v.encode("utf-8"))
chunks.append(b"\r\n")
for param, filename, ctype, data in files:
chunks.append(f"--{boundary}\r\n".encode("ascii"))
chunks.append(
f'Content-Disposition: form-data; name="{param}"; filename="{filename}"\r\n'.encode("utf-8")
)
chunks.append(f"Content-Type: {ctype}\r\n\r\n".encode("ascii"))
chunks.append(data)
chunks.append(b"\r\n")
chunks.append(f"--{boundary}--\r\n".encode("ascii"))
return b"".join(chunks)
def main() -> None:
cases = []
server = ThreadingHTTPServer(("127.0.0.1", 0), UploadServerHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
expected_sha = hashlib.sha256(MOCK_AVATAR).hexdigest()
# Case 1: Base64-encoded PNG form upload (AsyncHttpClient pattern)
b64_img = base64.b64encode(MOCK_AVATAR).decode("ascii")
body1 = urllib.parse.urlencode({"img": b64_img}).encode("utf-8")
conn.request("POST", "/postIcon", body=body1, headers={"Content-Type": "application/x-www-form-urlencoded"})
r1 = conn.getresponse()
p1 = json.loads(r1.read().decode("utf-8"))
actual1 = {"status": r1.status, "len": p1["decoded_len"], "sha_ok": p1["sha256"] == expected_sha}
expected1 = {"status": 200, "len": len(MOCK_AVATAR), "sha_ok": True}
cases.append({
"name": "base64_image_form_upload",
"summary": "Verify PNG byte Base64 encoding, form POST upload, and server-side SHA-256 verification.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: RFC 7578 multipart/form-data upload with text fields + binary file
boundary = "---------------------------7da2137580612"
mp_body = build_multipart(
boundary,
{"name": "tester", "id": "101"},
[("imagefile", "avatar.png", "image/png", MOCK_AVATAR)],
)
conn.request(
"POST",
"/uploadMultipart",
body=mp_body,
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
)
r2 = conn.getresponse()
p2 = json.loads(r2.read().decode("utf-8"))
actual2 = {
"status": r2.status,
"fields": p2["fields"],
"filename": p2["files"]["imagefile"]["filename"],
"file_ctype": p2["files"]["imagefile"]["content_type"],
"file_sha_ok": p2["files"]["imagefile"]["sha256"] == expected_sha,
}
expected2 = {
"status": 200,
"fields": {"name": "tester", "id": "101"},
"filename": "avatar.png",
"file_ctype": "image/png",
"file_sha_ok": True,
}
cases.append({
"name": "multipart_form_data_upload",
"summary": "Verify multipart/form-data boundary framing with CRLF line endings for text fields and binary file.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: postXml with text/xml; charset=UTF-8
xml_payload = "<upload><file>demo.mp3</file></upload>"
conn.request(
"POST",
"/postXml",
body=xml_payload.encode("utf-8"),
headers={"Content-Type": "text/xml; charset=UTF-8"},
)
r3 = conn.getresponse()
p3 = json.loads(r3.read().decode("utf-8"))
conn.close()
actual3 = {"status": r3.status, "content_type": p3["content_type"], "xml_body": p3["xml_body"]}
expected3 = {"status": 200, "content_type": "text/xml; charset=UTF-8", "xml_body": xml_payload}
cases.append({
"name": "post_xml_payload",
"summary": "Verify text/xml; charset=UTF-8 POST upload matching SocketHttpRequester.postXml.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Verify CRLF requirement vs legacy source typo '/r/n'
valid_crlf = b"\r\n"
typo_slash = b"/r/n"
actual4 = {
"crlf_bytes": list(valid_crlf),
"slash_typo_invalid": typo_slash != valid_crlf,
"boundary_has_crlf": b"\r\n" in mp_body and b"/r/n" not in mp_body,
}
expected4 = {"crlf_bytes": [13, 10], "slash_typo_invalid": True, "boundary_has_crlf": True}
cases.append({
"name": "multipart_crlf_protocol_check",
"summary": "Verify HTTP multipart delimiters require CRLF (0x0D 0x0A) rather than literal '/r/n' typo.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
finally:
server.shutdown()
server.server_close()
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
sys.exit(main())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-upload-file-lab/explore-tutorial-upload-file.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-upload-file.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1964.zip