1.客戶端程序
import requests
import os
# 指定服務(wù)器的URL
url = "http://192.168.1.9:8000/upload"
# 壓縮包文件路徑
folder_name = "upload"
file_name = "test.7z"
headers = {
'Folder-Name': folder_name,
'File-Name': file_name
}
# 發(fā)送POST請求,并將壓縮包作為文件上傳
with open(file_name, 'rb') as file:
response = requests.post(url, data=file,headers=headers)
# 檢查響應(yīng)狀態(tài)碼
if response.status_code == 200:
print("文件上傳成功!")
else:
print("文件上傳失?。?)
os.system('pause')
文章來源:http://www.zghlxwxcb.cn/news/detail-722372.html
2.服務(wù)端程序
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
# Define the request handler class
class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Send response status code
self.send_response(200)
# Send headers
self.send_header('Content-type', 'text/html')
self.end_headers()
path = self.path
if path == '/':
response_content = b'Hello, world!'
elif path == '/about':
response_content = b'This is the about page.'
else:
response_content = b'Page not found.'
# Send response content
self.wfile.write(response_content)
def do_POST(self):
client_address = self.client_address[0]
client_port = self.client_address[1]
print("client from:{}:{}".format(client_address,client_port))
path = self.path
print(path)
if path == '/upload':
content_length = int(self.headers['Content-Length'])
print(self.headers)
filename = self.headers.get('File-Name')
foldname = self.headers.get('Folder-Name')
#print(filename)
#print(foldname)
# 如果目錄不存在,創(chuàng)建目錄
os.makedirs(foldname, exist_ok=True)
filename = os.path.join(foldname, filename)
print(filename)
# 讀取請求體中的文件數(shù)據(jù)
file_data = self.rfile.read(content_length)
# # 保存文件
with open(filename, 'wb') as file:
file.write(file_data)
# 發(fā)送響應(yīng)
self.send_response(200)
self.end_headers()
self.wfile.write(b'File received and saved.')
else:
self.send_response(404)
self.end_headers()
# Specify the server address and port
host = '192.168.1.9'
port = 8000
# Create an HTTP server instance
server = HTTPServer((host, port), MyRequestHandler)
print("Server started on {}:{}".format(host,port))
# Start the server and keep it running until interrupted
server.serve_forever()
文章來源地址http://www.zghlxwxcb.cn/news/detail-722372.html
到了這里,關(guān)于http post協(xié)議發(fā)送本地壓縮數(shù)據(jù)到服務(wù)器的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!