python POST 请求文件 + 数据

python POST requests with file + data

我正在尝试通过 API 上传需要作为表格发送的图片和信息。我尝试使用 "files" 选项,请求提供没有成功。它给了我以下错误:

AttributeError: 'int' object has no attribute 'read'

我试过的代码行是:

r = requests.post(url, headers=header, files = {'imageFile' :    open('test_pic/1.jpg'), 'ticket' : ticket}, verify=False)

干杯弗洛里安

有几件事可以尝试:

  1. 如果您使用的是 Windows,请确保将 b 添加到 open 的文件权限中:

    open('filename', 'rb')
    

    这将确保文件被读取为二进制文件,否则可能会导致一些错误

  2. 发送多个文件时,需要传入一个元组列表,而不是字典:

    >>> multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
                  ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]
    >>> r = requests.post(url, files=multiple_files)
    

    这是根据online documentation

files = {'imageFile' :    open('test_pic/1.jpg'), 'ticket' : ticket}

ticketint 类型吗?我刚刚遇到同样的问题,文件中的值必须是 strbytesbytearray 或文件对象(这将导致读取操作),请参阅请求的 [=19] 中的详细信息=](函数_encode_files())