1. 程式人生 > 實用技巧 >檔案上傳下載程式碼

檔案上傳下載程式碼

#server端
import socketserver
import hashlib
import struct
import json
import os
import sys
DownLoad_path = 'H:\Python 學習檔案\大作業及複習\上傳'
upload_path = 'H:\Python 學習檔案\大作業及複習\測試'
file_list = ['測試-1.mp4','測試-2.mp4','測試-3.mp4']
def my_send(conn,dic):
jd = json.dumps(dic)
res = struct.pack('i',len(jd))
conn.send(res)
conn.send(jd.encode('utf-8'))
def my_recv(conn):
res = conn.recv(4)
res = struct.unpack('i',res)[0]
dic = conn.recv(res).decode('utf-8')
return json.loads(dic)
def get_md5(user,pwd):
m = hashlib.md5(user.encode('utf-8'))
m.update(pwd.encode('utf-8'))
return m.hexdigest()
def login(conn):
user_info = my_recv(conn)
with open('userinfo') as f:
for line in f:
username,password = line.strip().split('|')
print(username,password)
if username == user_info['username'] and password == get_md5(user_info['username'],user_info['password']):
result = True
print(result)
break
else:
result = False
dic = {'operator': 'login', 'result': result}
my_send(conn,dic)
return result
def download(conn):
file_dic = my_recv(conn)
path = os.path.join(DownLoad_path,file_dic['file_name'])
print(path)
with open(path,mode='wb') as f:
while file_dic['file_size'] > 0:
content = conn.recv(1024)
f.write(content)
file_dic['file_size'] -= len(content)
print('檔案上傳完成')

def upload(conn):
my_send(conn,file_list)
file_name = my_recv(conn)
path = os.path.join(upload_path,file_name['file_name'])
file_size = os.path.getsize(path)
file_dic = {
'file_name': file_name['file_name'],
'file_size': file_size
}
my_send(conn, file_dic)
with open(path, mode='rb') as f:
while file_size > 0:
content = f.read(1024)
conn.send(content)
file_size -= len(content)


class Myserver(socketserver.BaseRequestHandler):
def handle(self):
conn = self.request
while True:
try:
flag = login(conn)
if flag:
fun_dic = my_recv(conn)
print(fun_dic)
if fun_dic['function'] == 'download':
getattr(sys.modules[__name__],fun_dic['function'])(conn)
elif fun_dic['function'] == 'upload':
getattr(sys.modules[__name__], fun_dic['function'])(conn)
except OSError:
break
server = socketserver.ThreadingTCPServer(('127.0.0.1',9001),Myserver)
server.serve_forever()



#client端
import socket
import struct
import json
import os
import sys
upload_path = 'H:\Python 學習檔案\大作業及複習\下載'
def my_send(sk,dic):
jd = json.dumps(dic)
res = struct.pack('i',len(jd))
sk.send(res)
sk.send(jd.encode('utf-8'))
def my_recv(sk):
res = sk.recv(4)
res = struct.unpack('i',res)[0]
dic = sk.recv(res).decode('utf-8')
return json.loads(dic)
def login():
user = input('請輸入你的使用者名稱:').strip()
pwd = input('請輸入你的密碼:').strip()
user_info = {'username': user,'password' :pwd }
my_send(sk,user_info)
status_dic = my_recv(sk)
if status_dic['result'] == True:
print('登入成功')
return True
else:
print('登入失敗')
return False
def download(sk):
path = input('請輸入上傳的檔案地址:').strip()
file_size = os.path.getsize(path)
file_name = os.path.basename(path)
file_dic = {
'file_name' : file_name,
'file_size' : file_size
}
my_send(sk,file_dic)
with open(path,mode='rb') as f:
while file_size > 0:
content = f.read(1024)
sk.send(content)
file_size -= len(content)
print('檔案上傳完成')
def upload(sk):
file_list = my_recv(sk)
for index,file_name in enumerate(file_list,1):
print(index,file_name)
num = input('請選擇要下載的內容:').strip()
if num.isdecimal() and 0 < int(num) < 4:
file_name = {'file_name' :file_list[int(num)-1]}
my_send(sk,file_name)
file_dic = my_recv(sk)
path = os.path.join(upload_path, file_dic['file_name'])
with open(path, mode='wb') as f:
while file_dic['file_size'] > 0:
content = sk.recv(1024)
f.write(content)
file_dic['file_size'] -= len(content)
print('下載成功')

sk = socket.socket()
server_ip = ('127.0.0.1',9001)
sk.connect(server_ip)
oper_lst = ['download','upload']
while True:
ret = login()
if ret:
while True:
print('請選擇功能:')
for index,opt in enumerate(oper_lst,1):
print(index,opt)
num = input('請輸入你要選擇的功能序號:').strip()
fun_dic = {
'function' : oper_lst[int(num)-1]
}
my_send(sk,fun_dic)
if num.isdecimal() and 0 < int(num) < 3:
print(oper_lst[int(num)-1])
getattr(sys.modules[__name__],oper_lst[int(num)-1])(sk)