上传下载
Posted zhigu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传下载相关的知识,希望对你有一定的参考价值。
1 import json 2 import struct 3 import socketserver 4 import operate_handler 5 class MyFTP(socketserver.BaseRequestHandler): 6 def handle(self): 7 conn = self.request 8 length = conn.recv(4) 9 length = struct.unpack(‘i‘,length)[0] 10 opertate = (conn.recv(length)).decode(‘utf-8‘) 11 opertate_dic = json.loads(opertate) 12 opt = opertate_dic[‘operate‘] 13 usr = opertate_dic[‘user‘] 14 print(opt,usr) 15 getattr(operate_handler,opt)(conn,usr) 16 17 socketserver.TCPServer.allow_reuse_address = True 18 server = socketserver.ThreadingTCPServer((‘127.0.0.1‘,9000),MyFTP) 19 server.serve_forever()
1 import os 2 import json 3 import struct 4 base_path = r‘D:骑士计划PYTHON1期day32ftpserver oot‘ 5 6 def upload(conn,usr): 7 fileinfo_len = conn.recv(4) 8 fileinfo_len = struct.unpack(‘i‘,fileinfo_len)[0] 9 fileinfo_str = (conn.recv(fileinfo_len)).decode(‘utf-8‘) 10 fileinfo_dic = json.loads(fileinfo_str) 11 file_path = os.path.join(base_path,usr,fileinfo_dic[‘filename‘]) 12 with open(file_path,‘wb‘) as f: 13 while fileinfo_dic[‘filesize‘]: 14 content = conn.recv(1024) 15 fileinfo_dic[‘filesize‘] -= len(content) 16 f.write(content) 17 print(‘接收完毕‘)
1 import os 2 import json 3 import struct 4 import socket 5 6 def my_send(sk,operate_info): 7 b_optinfo = (json.dumps(operate_info)).encode(‘utf-8‘) 8 num = struct.pack(‘i‘, len(b_optinfo)) 9 sk.send(num) 10 sk.send(b_optinfo) 11 12 # 上传 13 sk = socket.socket() 14 sk.connect((‘127.0.0.1‘,9000)) 15 16 # [登录,注册,退出] 17 18 # [‘上传‘,‘下载‘,‘退出‘] 19 operate_info = {‘operate‘:‘upload‘,‘user‘:‘luke‘} 20 my_send(sk,operate_info) 21 # 我选择一个文件 发送到server端 22 file_path = r‘D:6.udp协议.mp4‘ 23 # 发送文件信息 24 file_name = os.path.basename(file_path) 25 file_size = os.path.getsize(file_path) 26 file_info = {‘filename‘:file_name,‘filesize‘:file_size} 27 my_send(sk,file_info) 28 # server端接收 写入 29 with open(file_path,‘rb‘) as f: 30 while file_size: 31 content = f.read(1024) 32 file_size -= len(content) 33 sk.send(content) 34 print(‘文件上传完毕‘)
以上是关于上传下载的主要内容,如果未能解决你的问题,请参考以下文章