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)

posted on 2021-05-15 20:20  BionExit  阅读(775)  评论(0编辑  收藏  举报

导航