Search code examples
pythonpostfile-uploadpython-requestsvk

Send file using POST from a Python


I have the url, where I need to send a video file. For this reason i wrote this code:

import requests

upload_url = 'https://cs506200.vk.me/upload_video_new.php?act=add_video&mid=21844505&oid=21844505&vid=171170813&fid=0&tag=93bb46ee&hash=e238f469a32fe7eee85a&swfupload=1&api=1'
file_ = {'file': ('video.mp4', open('video.mp4', 'rb'))}
r = requests.post(upload_url, files=file_)

print (r.text)

I get an error: {"error":"invalid file"}

But in this case:

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="utf-8">
 </head>
 <body>  
<form enctype="multipart/form-data" action="https://cs506200.vk.me/upload_video_new.php?act=add_video&mid=21844505&oid=21844505&vid=171170813&fid=0&tag=93bb46ee&hash=e238f469a32fe7eee85a&swfupload=1&api=1" method="POST" target="_blank">

<input type="file" name="video_file" />

<input type="submit" value="submit" name="submit" />
</form>
 </body>
</html>

All working fine. What am I doing wrong?


Solution

  • You are using the wrong field name:

    file_ = {'file': ('video.mp4', open('video.mp4', 'rb'))}
    

    That names the field file while your form uses video_file:

    <input type="file" name="video_file" />
    

    Using the right field name is important, correct your parameters:

    file_ = {'video_file': ('video.mp4', open('video.mp4', 'rb'))}