python 客户端上传文件到服务端
时间: 2023-08-17 19:12:31 浏览: 97
上传文件到服务器可以使用Python的socket模块,下面是一个简单的示例代码:
服务端代码:
```python
import socket
HOST = '0.0.0.0'
PORT = 5000
def receive_file(conn, filesize, filename):
with open(filename, 'wb') as f:
data = conn.recv(1024)
total_received = len(data)
f.write(data)
while total_received < filesize:
data = conn.recv(1024)
total_received += len(data)
f.write(data)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
print('Listening on port', PORT)
conn, addr = s.accept()
print('Connected by', addr)
data = conn.recv(1024)
filesize, filename = data.decode().split(',')
filesize = int(filesize)
receive_file(conn, filesize, filename)
```
客户端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 5000
def send_file(conn, filename):
filesize = str(os.path.getsize(filename))
conn.sendall((filesize + ',' + filename).encode())
with open(filename, 'rb') as f:
data = f.read(1024)
while data:
conn.send(data)
data = f.read(1024)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
send_file(s, 'file_to_upload.txt')
```
在客户端代码中,我们首先获取要上传的文件的大小和文件名,并将其发送给服务器。然后我们打开文件,将其分块读入,每次读入1024字节,并将其发送到服务器。
在服务端代码中,我们接受客户端发送的文件大小和文件名,并通过receive_file函数将文件接收到服务器上。
需要注意的是,在实际应用中,我们还需要对网络连接和文件操作进行一些错误处理和异常处理。
阅读全文