[python網路程式設計]檔案上傳

hide_in_darkness發表於2020-10-25

檔案上傳

文字檔案上傳

  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()

相關文章