简体   繁体   中英

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 .

I'm sure that server works fine, because if I send the same file to the same URL with curl it works:

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM