我正在尝试使用Python中的POST请求(请求库)上传文件。
我得到HTTP 400 error
作为回复。我认为这是因为我的POST请求不是它应该的格式。有关如何将POST请求1转换为2的任何想法吗?
代码:
files = {"file": ("test-file.txt", open("c:/users/johndoe/desktop/test-file.txt", "rb"), "text/plain")}
response = webdriver.request("POST", "https://something.com/attachments", files = files)
我目前的情况(1):
--d9bd23df892242a489b0f638d62502a6
Content-Disposition: form-data; name="file"; filename="test-file.txt"
Content-Type: text/plain
This is a test file.
Regards,
John Doe
--d9bd23df892242a489b0f638d62502a6--
我应该拥有什么(2):
-----------------------------26789175756830
Content-Disposition: form-data; name="fileName"
test-file.txt
-----------------------------26789175756830
Content-Disposition: form-data; name="fileSize"
45
-----------------------------26789175756830
Content-Disposition: form-data; name="description"
undefined
-----------------------------26789175756830
Content-Disposition: form-data; name="file"; filename="test-file.txt"
Content-Type: text/plain
This is a test file.
Regards,
John Doe
-----------------------------26789175756830--
我认为我需要添加(3):
-----------------------------26789175756830
Content-Disposition: form-data; name="fileName"
test-file.txt
-----------------------------26789175756830
Content-Disposition: form-data; name="fileSize"
45
-----------------------------26789175756830
Content-Disposition: form-data; name="description"
undefined
-----------------------------26789175756830
答案 0 :(得分:1)
您必须明确指定字段fileName
,fileSize
和description
,因为请求不会自动为您生成:
import os
import requests
filepath = 'foo'
files = {'file': open(filepath, 'rb')}
data = {
'fileName': filepath,
'fileSize': os.path.getsize(filepath),
'description': 'undefined'
}
response = requests.post('http://www.example.com/', data=data, files=files);
这会生成如下请求:
POST / HTTP/1.1
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate
Host: www.example.com
User-Agent: python-requests/2.13.0
Content-Length: 439
Content-Type: multipart/form-data; boundary=75a7213b6b4f493fabe26feeafb8551c
Http.Entity.Parser.Multipart.Tempdir: /tmp/pZjDE
--75a7213b6b4f493fabe26feeafb8551c
Content-Disposition: form-data; name="description"
undefined
--75a7213b6b4f493fabe26feeafb8551c
Content-Disposition: form-data; name="fileSize"
16
--75a7213b6b4f493fabe26feeafb8551c
Content-Disposition: form-data; name="fileName"
foo
--75a7213b6b4f493fabe26feeafb8551c
Content-Disposition: form-data; name="file"; filename="foo"
contents of foo
--75a7213b6b4f493fabe26feeafb8551c--