How to get filename from Content-Disposition in headers

前端 未结 3 1224
悲哀的现实
悲哀的现实 2020-12-29 03:36

I am downloading a file with Mechanize and in response headers there is a string:

Content-Disposition: attachment; filename=myfilename.txt

3条回答
  •  鱼传尺愫
    2020-12-29 03:45

    First get the value of the header by using mechanize, then parse the header using the builtin cgi module.

    To demonstrate:

    >>> import mechanize
    >>> browser = mechanize.Browser()
    >>> response = browser.open('http://example.com/your/url')
    >>> info = response.info()
    >>> header = info.getheader('Content-Disposition')
    >>> header
    'attachment; filename=myfilename.txt'
    

    The header value can then be parsed:

    >>> import cgi               
    >>> value, params = cgi.parse_header(header)
    >>> value
    'attachment'
    >>> params
    {'filename': 'myfilename.txt'}
    

    params is a simple dict so params['filename'] is what you need. It doesn't matter whether the filename is wrapped in quotes or not.

提交回复
热议问题