python请求上传文件到网站

时间:2017-08-03 09:31:01

标签: python python-3.x python-requests

这是我尝试过的,但它没有用。我尝试了其他一些东西,但它也提供了相同的响应

  

'{“success”:false,“errorcode”:400,“description”:“没有输入文件”}'

import requests

headers = {

    'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryXt3hSEPnfRBwBjIn',
    'Cookie': 'PHPSESSID=nsj01cb9864k1cb0rsga25o243; _ga=GA1.2.1065172575.1499660348; _gid=GA1.2.658410458.1501748127',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
}

url = 'http://pomf.cat/upload.php'
print(open('geckodriver.log', 'rb').read())
files = {'file': open('geckodriver.log', 'rb')}


r = requests.post(url, files=files, headers=headers)

print(r.text)

尝试了一个不同的文件得到了相同的答案

import requests

url = 'http://pomf.cat/upload.php'

files = {'file': open('test.txt', 'rb')}

print(files)
>>>{'file': b'Hello!'}
print(open("test.txt").read())
>>>Hello!
r = requests.post(url, files=files)
print(r.text)
>>>{"success":false,"errorcode":400,"description":"No input file(s)"}

1 个答案:

答案 0 :(得分:3)

你看文件了吗?您必须阅读文件并发送数据,而不仅仅是名称:

http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

我调查了一下这个pomf(主要是谷歌搜索)并找到了有趣的解决方案(查看文件的dict键):

>>> files = {'files[]': open('links.txt', 'rb')}
>>> response = requests.post(url, files=files)
>>> response.text
'{"success":true,"files":[{"hash":"316d880916ce07d93f42f6e28c97b004c5f450e3","name":"links.txt","url":"aaztfg.txt","size":1319,"deletion":"f455a0aae7c2665685cc6302f6c8ccd77dfd6f2e"}]}'
>>>