使用Python从POST发送文件

时间:2015-07-04 09:35:03

标签: python post file-upload python-requests vk

我有网址,我需要发送视频文件。 出于这个原因,我写了这段代码:

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)

我收到错误: {"错误":"文件无效"}

但在这种情况下:

<!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>

一切正常。 我做错了什么?

1 个答案:

答案 0 :(得分:7)

您使用了错误的字段名称:

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

当您的表单使用file时,该字段为video_file命名:

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

使用正确的字段名称非常重要,请更正您的参数:

file_ = {'video_file': ('video.mp4', open('video.mp4', 'rb'))}
相关问题