zoukankan      html  css  js  c++  java
  • Python 通过Request上传(form-data Multipart)下载文件

    下载文件

    import os
    import requests
    
    base_dir = os.path.abspath(os.path.dirname(__file__))
    file_path = os.path.join(base_dir, 'FileDownload', time.strftime("%F")) # 下载路径为 ./FileDownload/YYYY-MM-DD
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    download_file_name = 'a.txt' # 下载文件名
    
    download_file_addr = os.path.join(file_path, download_file_name)
    
    url = "http://contoso.com/1.txt" 下载地址
    
    r = requests.get(url)
    with open(download_file_addr, 'wb') as f:
        f.write(r.content)
    r.close()
    

    上传文件

    上传文件使用requests_toolbelt,满足Multipart的要求

    import requests
    from requests_toolbelt.multipart.encoder import MultipartEncoder
    
    upload_file_path = '/home/upload/1.txt' # 需要上传的文件路径
    file_name = '1.txt'
    request_url = 'http://contoso.com/upload' # 文件上传API地址
    
    m = MultipartEncoder( # 按照实际api规范拼接Mulipart参数,如果只上传文件,留file即可
      fields={
          'username': username,
          'password': password,
          'repoId': repoid,
          'parentDir': parent_dir,
          'replace': replace,
          'relativePath': relativePath,
          'file': (file_name, open(upload_file_path , 'rb'), 'text/plain')
      }
    )
    
    headers = {
        'Content-Type': m.content_type,
    }
    
    r = requests.post(request_url, data=m, headers=headers)
    result = json.loads(r.text)
    
  • 相关阅读:
    单词接龙
    字符串,字符数组
    马的遍历
    约瑟夫问题
    扫雷游戏
    寻找道路
    传纸条
    数的划分
    火柴棒等式
    火星人
  • 原文地址:https://www.cnblogs.com/bionexit/p/14772430.html
Copyright © 2011-2022 走看看