[英]Upload file with python requests not working
Note: I've already read all related questions & answers and tried that solutions without success.注意:我已经阅读了所有相关的问题和答案,并尝试了这些解决方案但没有成功。
I'm trying to upload file to the server with the following code:我正在尝试使用以下代码将文件上传到服务器:
with open('test.mp4', 'rb') as f:
r = requests.post(
url,
headers={
'Content-Type': 'multipart/form-data',
},
data=f
)
But request always fails with:但请求总是失败:
requests.exceptions.ConnectionError: ('Connection aborted.', BrokenPipeError(32, 'Broken pipe'))
I've also tried to send it as files
, not data
.我也尝试将其作为files
发送,而不是data
。
I'm sure that server works fine, because if I send the same file to the same URL with curl it works:我确信服务器工作正常,因为如果我将相同的文件发送到同一个 URL 和 curl 它可以工作:
curl -vvv -i -X POST -H "Content-Type: multipart/form-data" -F "data=@test.mp4" "https://vu.mycdn.me/upload.do?someskippedparams"
What's wrong with my code?我的代码有什么问题?
Normally this should work通常这应该工作
with open('test.mp4', 'rb') as f:
r = requests.post(
url,
headers={
'Content-Type': 'multipart/form-data',
},
files={ "data": f},
)
But somehow it fails for your server.但不知何故,它对您的服务器失败了。 Providing file name and mime type explicitly seems to solve the problem.显式提供文件名和 mime 类型似乎可以解决问题。
fname = "test.mp4"
with open(fname, "rb") as f:
r = requests.post(
url,
files=[
("data", (os.path.basename(fname), f, "video/mp4")),
]
)
print(r.status_code)
print(r.text)
import requests
headers = {
'Content-Type': 'multipart/form-data',
}
params = (
('someskippedparams', ''),
)
files = {
'data': ('test.mp4', open('test.mp4', 'rb')),
}
response = requests.post('https://vu.mycdn.me/upload.do', headers=headers, params=params, files=files)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.