Content Disposition Filename Parse

Parse Content-Disposition headers for safe filename extraction with RFC 5987 support.

PythonFile Upload

Code

pythonsnippet
16 lines
from urllib.parse import unquote
import re

def parse_filename(header):
    if not header:
        return None
    m = re.search(r"filename\*=([^;]+)", header)
    if m:
        parts = m.group(1).split("'")
        if len(parts) == 3:
            return unquote(parts[2])
        return unquote(parts[-1])
    m = re.search(r'filename="?([^";]+)"?', header)
    if m:
        return m.group(1)
    return None

How it works

Content Disposition Filename Parse comes down to the function parse_filename.

From urllib it pulls unquote — the imports name exactly which library surface the snippet touches.

What to watch for

  • Plan for an install step: urllib is a real dependency, resolved by the package manager.

Putting it to use

Entry signature: def parse_filename(header)

parse_filename is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`urllib` — install it with the package manager before running.