如何使用 Requests 指定表单字段和文件类型

How to specify form field and file type with Requests

我想使用请求模块上传图片 (Python 3)。可悲的是,服务器以错误的方式回答了我的请求,说我应该只上传 jpg、png 或 gif 类型的文件。 我想我应该填写表格的每个字段,但我想弄清楚尽管我进行了所有测试。

这是 HTML 表格:

<form class="upload" enctype="multipart/form-data" action="?action=upload" method="post">
            <h3>Envoyez votre image !</h3>
    <input name="MAX_FILE_SIZE" value="15360000" type="hidden" /> 
    <input name="img" size="30" type="file" />
    <input value="Envoyer" type="submit" />
</form>

我使用这个 Python 代码:

with open(image, 'rb') as img:
    toup = {'img': (os.path.basename(image), img)}
    res= requests.post('http://url/?action=upload', files = toup)

如何填写MAX_FILE_SIZE字段并指定上传文件的类型?

MAX_FILE_SIZE 似乎是正常的 HTTP POST 数据:

with open(image, 'rb') as img:
    toup = {'img': (os.path.basename(image), img)}
    res= requests.post('http://url/?action=upload', files = toup, data={'MAX_FILE_SIZE': '15360000'})

您可以 set the mime type 文件:

toup = {'img': (os.path.basename(image), img, 'image/jpeg')}

要获得文件的准确 MIME,您可以使用 mimetypes 库。