2025-09-15_parsing-multipart-form-data.html


001| #:name::Parsing Multipart Form Data
002| #:link::https://thehardcorecoder.com/2025/09/15/parsing-multipart-form-data/
003| #:date::2025-09-15
004| #:code::
005| from cgi import FieldStorage
006| 
007| if __name__ == '__main__':
008|     form = FieldStorage()
009|     ...
010| 
011| #:code::
012| from sys import stdin
013| from os import environ
014| from urllib import parse
015| 
016| if __name__ == '__main__':
017|     # GET data...
018|     qs = environ.get('QUERY_STRING', '')
019|     get_dict = parse.parse_qs(qs)
020| 
021|     # POST data...
022|     post_len = int(environ.get('CONTENT_LENGTH', 0))
023|     post_txt = stdin.read(post_len)
024|     post_dict = parse.parse_qs(post_txt)
025| 
026|     form = dict(**get_dict, **post_dict)
027|     params = {}
028|     for name in sorted(form):
029|         value = form[name]
030|         # If it's a list of multiple items...
031|         if 1 < len(value):
032|             for ix,v in enumerate(value, start=1):
033|                 params[f'{name}-{ix}'] = v
034|         # Otherwise it's just a name:value pair...
035|         else:
036|             params[name] = value[0]
037|     ...
038| 
039| #:code::
040| if __name__ == '__main__':
041|     ...
042|     for name in sorted(form):
043|         ...
044|         # Load filename and file object into params...
045|         if name == 'fn':
046|             fobj = form['fn']
047|             params['fn'] = fobj.filename
048|             params['fp'] = fobj.file
049|     ...
050|     ...
051| 
052|     # Use filename and file data...
053|     fn = kwargs['fn']
054|     bs = kwargs['fp'].read()
055|     ...
056| 
057| #:code::
058| txt = 'Content-Disposition: form-data; name="fn"; filename="foo.py"'
059| 
060| class MimeHeader (tuple):
061|     '''\
061| MIME Header class. Parses text to a defined tuple.
061| 
061| Expected text has the syntax:
061|     <name>: <text> [; name=value [; ...]]
061| 
061| Created tuple is:
061|     (name, text, fields)
061| 
061| Properties:
061|     name        -field name
061|     text        -field text
061|     fields      -dictionary of name:value pairs
061| 
061| Methods:
061|     str(obj)    -printable version
061|     repr(obj)   -debugging version
061| '''

062|     def __new__ (cls, text):
063|         '''New MimeHeader instance.'''
064| 
065|         # Split text into name and value parts...
066|         parts = text.partition(': ')
067|         if parts[1] != ': ':
068|             ValueError(f'Invalid MIME Header (no ": "): "{text}"')
069| 
070|         # Split the value into fields...
071|         subparts = parts[2].split('; ')
072|         value = subparts[0]
073| 
074|         fields = {}
075|         for subp in subparts[1:]:
076|             # Split field into name and value...
077|             key,val = subp.split('=', maxsplit=1)
078|             # Add field; remove any surrounding double-quotes...
079|             fields[key] = val.strip('"')
080| 
081|         # Delegate creating new instance to tuple...
082|         return super().__new__(cls, (parts[0], value, fields))
083| 
084|     @property
085|     def name (self): return self[0]
086| 
087|     @property
088|     def text (self): return self[1]
089| 
090|     @property
091|     def fields (self): return self[2]
092| 
093|     def __str__ (self):
094|         return f'{self.name}: {self.text}'
095| 
096|     def __repr__ (self):
097|         return f'<{type(self).__name__} @{id(self):08x}>'
098| 
099| 
100| if __name__ == '__main__':
101|     hdr = MimeHeader(txt)
102|     print(f'Header: {hdr} {hdr!r}')
103|     print(f'Header Name: {hdr.name}')
104|     print(f'Header Text: {hdr.text}')
105|     print('Header Fields:')
106|     for nam,val in hdr.fields.items():
107|         print(f'> {nam}: {val}')
108|     print()
109| 
110| #:code::
111| from examples import MimeHeader
112| 
113| EOL  = ord('\n')
114| CR   = ord('\r')
115| DASH = ord('-')
116| 
117| def parse_multipart_form (content_type:str, byte_string:bytes) -> tuple:
118|     '''\
118| Parse Multipart Form Data.
118| 
118| Arguments:
118|     content_type    -content header text
118|     byte_string     -form data bytes
118| 
118| Returns:
118|     tuple: (form, filename, filetype, filedata)
118| 
118|     Note: the last three field will be None if no file data.
118| '''

119|     form = {}               # form data to be returned
120|     parthdrs = {}           # temp dictionary for part headers
121|     content = []            # buffer for building file content
122|     buf = []                # temp buff for building strings
123|     state = 'prefix'        # current state
124|     boundary = None         # part separator string
125| 
126|     # Parse the content-type header to get the multipart boundary...
127|     ix = content_type.index('boundary=') + len('boundary=')
128|     boundary = content_type[ix:].lstrip('-')
129| 
130|     # Iterate over the bytes of the data...
131|     for bx in byte_string:
132| 
133|         if state == 'prefix':
134|             # Accumulate dashes...
135|             if bx == DASH:
136|                 buf.append(bx)
137|                 continue
138|             # Not a dash; separator text begins...
139|             if len(buf) < 6:
140|                 raise SyntaxError(f'Expected six hyphens, not {len(buf)}.')
141|             # Add first separator character to buffer...
142|             buf = [bx]
143|             state = 'sep'
144|             continue
145| 
146|         if state == 'sep':
147|             # End of separator...
148|             if bx == EOL:
149|                 sep_str = ''.join(chr(b) for b in buf)
150|                 if not sep_str.startswith(boundary):
151|                     raise SyntaxError(f'Invalid Separator: "{sep_str}"')
152|                 buf = []
153|                 parthdrs = {}
154|                 state = 'part.start'
155|                 continue
156|             # Ignore CR characters...
157|             if bx == CR:
158|                 continue
159|             # Add separator character to buffer...
160|             buf.append(bx)
161|             continue
162| 
163|         if state == 'part.start':
164|             # Blank line (instead of header text)...
165|             if bx == EOL:
166|                 # End of part headers...
167|                 content = []
168|                 state = 'part.data'
169|                 continue
170|             # Ignore CR characters...
171|             if bx == CR:
172|                 continue
173|             # Add first part header character to buffer...
174|             buf = [bx]
175|             state = 'part.hdr'
176|             continue
177| 
178|         if state == 'part.hdr':
179|             # Handle end of line...
180|             if bx == EOL:
181|                 txt = ''.join(chr(b) for b in buf)
182|                 hdr = MimeHeader(txt)
183|                 parthdrs[hdr.name.lower()] = hdr
184|                 state = 'part.start'
185|                 continue
186|             # Ignore CR characters...
187|             if bx == CR:
188|                 continue
189|             # Add part header character to buffer...
190|             buf.append(bx)
191|             continue
192| 
193|         if state == 'part.data':
194|             # A dash might mean a separator...
195|             if bx == DASH:
196|                 buf = [bx]
197|                 state = 'test.prefix'
198|                 continue
199|             # Add content byte to buffer...
200|             content.append(bx)
201|             continue
202| 
203|         if state == 'test.prefix':
204|             # Not a dash; start of separator...
205|             if bx != DASH:
206|                 # Not a separator; add to content and resume...
207|                 if len(buf) != 6:
208|                     # Not a separator...
209|                     content.extend(buf)
210|                     content.append(bx)
211|                     state = 'part.data'
212|                     continue
213|                 # Got 6 dashes; might be a separator...
214|                 buf = [bx]
215|                 state = 'test.sep'
216|                 continue
217|             # Add character to possible prefix string...
218|             buf.append(bx)
219|             continue
220| 
221|         if state == 'test.sep':
222|             # End of line; test separator...
223|             if bx == EOL:
224|                 txt = (''.join(chr(c) for c in buf)).strip()
225|                 if txt != boundary:
226|                     # Not a separator...
227|                     content.extend(buf)
228|                     content.append(bx)
229|                     state = 'part.data'
230|                     continue
231|                 # It is a separator; get disposition header...
232|                 cdisp = parthdrs['content-disposition']
233|                 name = cdisp.fields['name']
234|                 # Add file content (bytes) to form (strip trailing CR-LF)...
235|                 form[name] = bytes(content[0:-2])
236|                 # Add the disposition header...
237|                 form[f'{name}.disp'] = cdisp
238|                 # If content-type header provided...
239|                 if 'content-type' in parthdrs:
240|                     # Add to form...
241|                     form[f'{name}.type'] = parthdrs['content-type']
242|                 # Get ready for next part...
243|                 buf = []
244|                 parthdrs = {}
245|                 state = 'part.start'
246|                 continue
247|             # Add to separator string...
248|             buf.append(bx)
249|             continue
250| 
251|     # Extract the filename, filetype, and file data for convenience...
252|     filedata, filename, filetype = None,None,None
253|     for name in form:
254|         if name == 'fn':
255|             filedata = form['fn']
256|             filetype = form['fn.type'].text
257|             filename = form['fn.disp'].fields['filename']
258|             if filetype.startswith('text'):
259|                 filedata = str(filedata, encoding='utf8')
260|             continue
261| 
262|         # Also convert simple fields from bytes to strings...
263|         if '.' not in name:
264|             txt = form[name]
265|             if isinstance(txt,bytes):
266|                 form[name] = str(txt, encoding='utf8')
267| 
268|     form['fn.name'] = filename
269|     return (form, filename, filetype, filedata)
270| 
271| #:code::
272| from sys import argv
273| from examples import parse_multipart_form
274| 
275| FName = r'C:\Demo\Python\multipart-1.txt'
276| CType = r'multipart/form-data; boundary=----WebKitFormBoundaryFvgrhoe2FqQdLu4J'
277| 
278| def test_parser (file_name:str, content_type:str) -> tuple:
279|     '''Function to exercise Multipart parser.'''
280| 
281|     # Read multipart form data from file (binary mode)...
282|     fp = open(file_name, mode='rb')
283|     try:
284|         data = fp.read()
285|         print(f'loaded: {file_name}')
286|         print(f'bytes: {len(data)}')
287|         print()
288|     except:
289|         raise
290|     finally:
291|         fp.close()
292| 
293|     # Parse the multipart form...
294|     form,fname,ftype,fdata = parse_multipart_form(content_type, data)
295| 
296|     # List the form data...
297|     for key in sorted(form):
298|         val = form[key]
299| 
300|         if key == 'fn':
301|             print(f'{key}: <filedata>')
302|             continue
303| 
304|         if isinstance(val, str):
305|             print(f'{key}: {val}')
306|             continue
307| 
308|         print(f'{key}: {form[key].text}')
309| 
310|     print()
311| 
312|     return (form, fname, ftype, fdata)
313| 
314| if __name__ == '__main__':
315|     print(f'autorun: {argv[0]}')
316| 
317|     file_name = argv[1] if 1 < len(argv) else FName
318|     content_type = argv[2] if 2 < len(argv) else CType
319| 
320|     print()
321|     form,fname,ftype,fdata = test_parser(file_name, content_type)
322|     print()
323| 
324| #:end:code::
325|