python实现文件上传功能
下面是客户端和服务端实现文件上传功能的程序实现代码,具体实现请写的很详细了,这里我就不废话直接贴代码。欢迎留言优化程序代码!!!
客户端文件上传功能代码
import os
import socket
# 创建客户端socket对象
client_socket = socket.socket()
# IP 和 Port
address = (IP, Port)
# 客户端连接
client_socket.connect(address)
# 文件路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
while True:
msg = input('>>> ').strip()
cmd, path = msg.split('|')
# 拼接路劲
path = os.path.join(BASE_DIR, path)
filename = os.path.basename(path)
# 文件大小
file_size = os.stat(path).st_size
file_info = 'post|%s|%s' % (filename, file_size)
client_socket.sendall(bytes(file_info, "utf8"))
# 打开文件路径,rb字节流模式读取文件
f = open(path, 'rb')
has_sent = 0
while has_sent != file_size:
data = f.read(1024)
client_socket.sendall(data)
has_sent += len(data)
f.close()
print("上传成功")
# if not msg:
# continue
# client_socket.send(msg.encode('utf-8'))
# data = client_socket.recv(1024)
# print(data.decode('utf-8'))
# 关闭套接字
client_socket.close()
服务器文件上传功能代码
import socket
import os
# 创建socket对象
server_socket = socket.socket()
# IP 和 Port
address = (IP, Port)
# 绑定IP和Prot
server_socket.bind(address)
server_socket.listen(3)
# 路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
while 1:
conn, addr = server_socket.accept()
while 1:
data = conn.recv(1024)
cmd, filename, filesize = str(data, 'utf8').split('|')
path = os.path.join(BASE_DIR, 'yuan', filename)
filesize = int(filesize)
# 打开文件位置,以'ab'追加模式写入
f = open(path, 'ab')
has_recerve = 0
while has_recerve != filesize:
data = conn.recv(1024)
f.write(data)
has_recerve += len(data)
f.close()