【问题标题】:Content-Type in for individual files in python requestspython请求中单个文件的Content-Type in
【发布时间】:2013-12-13 05:31:09
【问题描述】:

我想向在 python 烧瓶中运行的服务器请求文件和一些元信息。因此我的请求内容类型将是'multipart/form-data。有没有办法可以设置文件的内容类型,如图像/jpg、图像/gif 等... 如何设置文件的内容类型。有没有可能

【问题讨论】:

  • 你试过了吗?这听起来像是将在文档中解释的内容。
  • @SimeonVisser:虽然这是可能的,但实际上它没有记录在任何地方。
  • @MartijnPieters:很公平,看起来你已经回答了下面的问题。

标签: python request content-type


【解决方案1】:

如果您将每个文件规范设为元组,则可以将 mime 类型指定为第三个参数:

files = {
    'file1': ('foo.gif', open('foo.gif', 'rb'), 'image/gif'),
    'file2': ('bar.png', open('bar.png', 'rb'), 'image/png'),
}
response = requests.post(url, files=files)

你也可以给第四个参数,它必须是一个字典,每个部分都有额外的标题。

【讨论】:

  • 在最新版本的 Requests 中不再有效
  • @Khertan:是什么让你这么想? documentation 还是一样的。您可以使用此处所示的(key, fileinfo) 元组序列和此处使用的字典。
  • @Khertan:我刚刚在 master 分支上再次尝试了这个,这仍然像我在这里展示的那样工作。
  • 确实很抱歉...不知道为什么这里的版本不测试元组的长度
【解决方案2】:

reference

    import requests

    url = "http://png_upload_example/upload"
    # files = [(<key>, (<filename>, open(<file location>, 'rb'), <content type>))]
    files = [('upload', ('thumbnail.png', open('thumbnail.png', 'rb'), 'image/png'))]

    response = requests.request("POST", url, files = files)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2011-08-11
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    相关资源
    最近更新 更多