Python 檔案上傳案例
阿新 • • 發佈:2022-05-11
'''
import requests
res = requests.get(
"https://vd2.bdstatic.com/mda-nae3n9ssk12en6we/sc/cae_h232_delogo/1642214352000767797/mda-nae3n9ssk12en6c7.mp4?v_from_s=hkapp-haokan-hbe&auth_key=1645862871-0-0-bc029a5e7ae5746e98a9d0ed826461e6&bcevod_channel=searchbox_feed&pd=1&cd=0&pt=3&logid=2271091750&vid=5617093822891991609&abtest=100815_2-17451_1&klogid=2271091750")
with open("圖片.jpg", "wb") as f:
f.write(res.content)
'''
'''
import socket
import json
# (1) 構建套接字物件,確定通訊協議
sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
# (2) 繫結IP和埠
ip_port = ("127.0.0.1", 6784)
sock.bind(ip_port)
# (3) 監聽最大排隊數
sock.listen(2)
# (4) 阻塞等待客戶端連線
while 1:
print("server is waiting...")
conn, addr = sock.accept()
# print("conn", conn)
# print("addr", addr)
while 1:
# (2)接受來自客戶端的檔案資訊
data_json = conn.recv(1024) # recv是一個阻塞函式
data = json.loads(data_json.decode())
print("data:", data)
file_size = data["params"]["file_size"]
file_name = data["params"]["file_name"]
# (3)將接收到的檔案資料一行行寫入到新檔案中
receive_data_len = 0
with open("" + file_name,"wb") as f:
while receive_data_len < file_size:
temp = conn.recv(1024)
f.write(temp)
receive_data_len += len(temp)
print("檔案上傳成功")
'''
'''
import socket
import os
import json
# (1) 構建套接字物件,確定通訊協議
sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
ip_port = ("127.0.0.1", 6784)
sock.connect(ip_port)
while 1:
# 客戶端給服務端傳送訊息
params = input("請輸入命令(比如上傳檔案put 檔案路徑):")
cmd, local_path = params.split(" ")
# (1) 將檔案資訊傳給服務端
file_size = os.path.getsize(local_path)
file_name = os.path.basename(local_path)
file_params = {"file_name": file_name, "file_size": file_size}
data = {"cmd": cmd, "params": file_params}
print("data", data)
sock.send(json.dumps(data).encode())
# (2) 迴圈讀取檔案,傳給server端
with open(local_path, "rb") as f:
for line in f:
sock.send(line)
print("檔案傳送完畢")
'''