开发者社区> 问答> 正文

python 钉钉文件上传

第一,现有的钉钉接口文件上传说明示例太过简单
第二,自己过python的requesets post方式进行:
将access_token,type设置到params,将media 设置到files,最后通过requests.request(method=method,url=url, **kwargs )上传,能上传,不过文件没有后缀,二进制数据都直接被当做文本在网页呈现,能否说一下python的上传思路?

展开
收起
蓝蓝天空 2017-01-08 10:19:14 10315 0
4 条回答
写回答
取消 提交回答
  • from urllib3 import encode_multipart_formdata
    import requests
    headers={}
    data={}
    url = 'https://oapi.dingtalk.com/media/upload?access_token=' + access_token + '&type=file'
    def post_files(url,headers,data,filename,filepath):

    """
        :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    """
    data['media']= ('test.py', open(r'C:\Users\Administrator\Desktop\test.py', 'rb').read())
    encode_data = encode_multipart_formdata(data)
    data = encode_data[0]
    headers['Content-Type'] = encode_data[1]
    r = requests.post(url, headers=headers, data=data)
    print(json.loads(r.text)["media_id"])
    

    from urllib3 import encode_multipart_formdata
    import requests
    headers={}
    data={}
    url = 'https://oapi.dingtalk.com/media/upload?access_token=' + access_token + '&type=file'
    def post_files(url,headers,data,filename,filepath):

    data['media']= ('test.py', open(r'C:\Users\Administrator\Desktop\test.py', 'rb').read())
    encode_data = encode_multipart_formdata(data)
    data = encode_data[0]
    headers['Content-Type'] = encode_data[1]
    r = requests.post(url, headers=headers, data=data)
    print(json.loads(r.text)["media_id"])
    2019-07-17 20:41:12
    赞同 展开评论 打赏
  • for filename in file_dict.keys():
      files[filename] = open(file_dict[filename], mode='rb')
    r = requests.post(url, data=data,files=files)
    

    如果你说的是钉钉这个接口的话:https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.JknMf3&treeId=172&articleId=104971&docType=1

    应该是用这种方式来上传,接口文档描述得确实不是很清晰,给的是java的代码示例,对于mutipart格式的接口来说,这个接口协议就是耍榴芒。

    2019-07-17 20:41:12
    赞同 展开评论 打赏
  • 建议楼主修改下问题描述,我也没看明白啊

    2019-07-17 20:41:12
    赞同 展开评论 打赏
  • 码农|Coder| Pythonista

    您具体的需求是什么呢?如果单纯是后缀问题,您可以在您自行的业务系统中处理的

    2019-07-17 20:41:12
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
钉钉小程序——为工作方式插上翅膀 立即下载
钉钉客户端自动化的应用 立即下载
使命必达 —— 钉钉企业级 消息服务的机遇与挑战 立即下载