python3使用requests和requests_toolbelt上传文件

首先安装requsetsrequests_toolbelt两个模块

pip install requests
pip install requests_toolbelt

代码:

import time
import datetime
import hashlib
import os
import random
import sys
import requests
import json

from requests_toolbelt.multipart.encoder import MultipartEncoder

url = 'http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0',
    'Referer': url
}

multipart_encoder = MultipartEncoder(
    fields = {
        'save_name': 'test.txt',
        'save_data': ('test.txt', open('test.txt', 'rb'), 'application/octet-stream')
    },
    boundary = '-----------------------------' + str(random.randint(1e28, 1e29 - 1))
)

headers['Content-Type'] = multipart_encoder.content_type
#请求头必须包含一个特殊的头信息,类似于Content-Type: multipart/form-data; boundary=${bound}

responseStr = requests.post(url, data=multipart_encoder, headers=headers)
print(responseStr.text)


你可能感兴趣的:(python)