请求:使用POST方法发送multipart/form-data数据

9

我的API:

class FileView(APIView):
    parser_classes = (MultiPartParser,)
    def post(self, request):
        do something with request.FILES.dict().iteritems()

我的requests文件:

try:
    headers = {
        'content-type': "multipart/form-data",
        'authorization': "Basic ZXNlbnRpcmVcYdddddddddddddd",
        'cache-control': "no-cache",
    }
    myfile = {"file": ("filexxx", open(filepath, "rb"))}

    response = requests.request("POST", verify=False, url=url, data=myfile, headers=headers)

    print(response.text)
except Exception as e:
    print "Exception:", e

错误:

"多部分表单解析错误 - 多部分中的无效边界:None"

如何正确地发布文件? 谢谢

requests.version '2.10.0'

1个回答

19

删除了头部的 'content-type',现在它可以工作了

try:
    headers = {
        'authorization': "Basic ZXNlbnRpcmVcYdddddddddddddd",
        'cache-control': "no-cache",
    }
    myfile = {"file": ("filexxx", open(filepath, "rb"))}

    response = requests.request("POST", verify=False, url=url, data=myfile, headers=headers)

    print(response.text)
except Exception as e:
    print "Exception:", e

2
让请求设置内容类型。在请求头中,content-type的值为 multipart/form-data; boundary=f0d7eb0b58c94f8ea3e665e28cffffdc 其中boundary会随着请求而改变。 - Bamcclur
是的!当 content-type='multipart/form-data 时,浏览器在发送 POST 请求时会添加 boundary 参数。因此,在 Python 中完全不需要手动添加。反爬虫工具如 Distill-Networks 等可以利用这个参数轻松检测到 Python 网络爬虫。 - SIslam
什么!我已经找了3天才找到这个解决方案。 - Loi Nguyen Huynh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接