Skip to main content
 首页 » 编程设计

python之从 Python 使用 POST 发送文件

2025年05月04日14findumars

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

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> 

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

请您参考如下方法:

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

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

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

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

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

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