如何从标题中的Content-Disposition获取文件名 [英] How to get filename from Content-Disposition in headers

查看:1560
本文介绍了如何从标题中的Content-Disposition获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mechanize下载文件,并且响应头中有一个字符串:

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

Content-Disposition: attachment; filename=myfilename.txt

是否有一种快速的标准方法来获取文件名值? 我现在想到的是:

Is there a quick standard way to get that filename value? What I have in mind now is this:

filename = f[1]['Content-Disposition'].split('; ')[1].replace('filename=', '')

但这看起来像是一种快速的肮脏"解决方案.

But it looks like a quick'n'dirty solution.

推荐答案

首先使用机械化获取标头的值,然后使用内置的

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

演示:

>>> 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'

然后可以解析标头值:

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

params是一个简单的字典,因此params['filename']是您所需要的. 文件名是否用引号引起来都没关系.

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.

这篇关于如何从标题中的Content-Disposition获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆