[python网络编程]文件上传

文件上传

文本文件上传

  1. server服务端
import socket
import json
import struct
import time


IP = ""
PORT = 0

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind((IP, PORT))

server.listen(5)

client, _ = server.accept()

size = struct.unpack("i", client.recv(4))[0]

time.sleep(0.5)

data = json.loads(client.recv(size).decode())

time.sleep(0.5)

content = client.recv(data['file_size'])

with open(data['file_name'], mode='wb') as f:
    f.write(content)

client.close()

server.close()

  1. client客户端
import socket
import os
import json
import struct
import time


IP = ""
PORT = 0
PATH = r"F:\python\data\temp.txt"

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect((IP, PORT))

file_name = os.path.basename(PATH)

file_size = os.path.getsize(PATH)

data = {
    'file_name': file_name,
    'file_size': file_size
}

msg = json.dumps(data)

print("正在向服务器发送名为{}的文件".format(file_name))

size = struct.pack("i", len(msg))
client.send(size)

time.sleep(0.5)

client.send(msg.encode())

time.sleep(0.5)

with open(PATH, mode='rb') as f:
    content = f.read()
    client.send(content)

client.close()

大文件上传

  1. server服务端
import socket
import json
import struct
import time


IP = ""
PORT = 0

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind((IP, PORT))

server.listen(5)

client, _ = server.accept()

size = struct.unpack("i", client.recv(4))[0]

time.sleep(0.5)

data = json.loads(client.recv(size).decode())

time.sleep(0.5)


with open(data['file_name'], mode='wb') as f:
    while data['file_size'] > 0:
        content = client.recv(1024)
        data['file_size'] = data['file_size'] - len(content)
        f.write(content)

client.close()

server.close()

  1. client客户端
import socket
import os
import json
import struct
import time


IP = ""
PORT = 0
PATH = r"F:\python\data\temp.txt"

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect((IP, PORT))

file_name = os.path.basename(PATH)

file_size = os.path.getsize(PATH)

data = {
    'file_name': file_name,
    'file_size': file_size
}

msg = json.dumps(data)

print("正在向服务器发送名为{}的文件".format(file_name))

size = struct.pack("i", len(msg))
client.send(size)

time.sleep(0.5)

client.send(msg.encode())

time.sleep(0.5)

with open(PATH, mode='rb') as f:
    while file_size > 0:
        content = f.read(1024)
        file_size = file_size - len(content)
        client.send(content)

client.close()
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页