简体   繁体   English

python请求中单个文件的内容类型

[英]Content-Type in for individual files in python requests

I want to request to my server running in python flask with file and some meta information.我想向在 python flask 中运行的服务器请求文件和一些元信息。 Hence my request content-Type will be 'multipart/form-data.因此,我的请求内容类型将是“multipart/form-data”。 Is there a way i can set the content type of file like image/jpg, image/gif etc... How do i set the content-type for the file.有没有办法设置文件的内容类型,如图像/jpg、图像/gif 等...我如何设置文件的内容类型。 Is it possible or not有没有可能

If you make each file specification a tuple, you can specify the mime type as a third parameter:如果将每个文件规范设为元组,则可以将 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)

You can give a 4th parameter as well, which must be a dictionary with additional headers for each part.你也可以给出第四个参数,它必须是一个字典,每个部分都有额外的标题。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Python请求的内容类型不正确 - Content-Type incorrect using Python Requests Python Flask,如何为静态文件(js)设置“Content-Type”? - Python Flask, how to set 'Content-Type' for static files (js)? 在某些请求的标头中,内容类型为空白 - Content-type is blank in the headers of some requests 在Python中更改内容类型 - Changing Content-Type in Python 如何在python-requests库中设置POST请求的内容类型? - How do I set the content-type for POST requests in python-requests library? Python请求,如何向multipart/form-data请求添加内容类型 - Python requests, how to add content-type to multipart/form-data request Python 请求不发送 {&quot;Content-Type&quot;:&quot;application/json&quot;} 标头或只是忽略 HTTP POST 中的正文 - Python requests not sending {"Content-Type":"application/json"} header or is just ignoring body in HTTP POST 如何根据服务器使用Python中的请求发送的Content-Type捕获响应? - How to capture the response based on the Content-Type sent by the server using requests in Python? python 请求不将我的 POST 数据作为内容类型发送:multipart/form-data auto - python requests not sending my POST data as content-type:multipart/form-data auto "如何使用 python 请求设置内容类型的边界?" - How can I set boundary of Content-type using python requests?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM