Python Socket实现文件上传:file_send与file_receive完整代码示例

许南星
许南星
发布时间:2026-10-13 | 7人浏览过
原创

本文通过Python socket模块实现文件上传功能,包含file_send.py发送端与file_receive.py接收端完整代码。程序通过指定端口8001建立连接,传输文件元数据后以二进制流形式读写文件,最终将指定文件保存至目标目录。

Python Socket文件上传实现概述

本文介绍利用Python socket模块进行文件上传的具体实现方法,文中提供了详细的代码示例,对读者学习或实际工作具有参考意义。

需要编写两个Python程序:file_send.py用于发起文件上传,file_receive.py用于接收并保存文件至指定目录。

接收端代码file_receive.py


#file_receive.py
import socket,subprocess,os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sk = socket.socket()
address = ('127.0.0.1',8001)
sk.bind(address)
sk.listen(3)
conn,addr = sk.accept()
fileinfo = conn.recv(1024)
filename,filesize = str(fileinfo,'utf8').split('|')
#filename = str(filename,'utf8')
#filesize = int(str(filesize,'utf8'))
path = os.path.join(BASE_DIR,'file_recv',filename)
f = open(path,'wb')
has_received = 0
while has_received != int(filesize):
  data = conn.recv(1024)
  f.write(data)
  has_received += len(data)

f.close()
print('well done')
sk.close()

发送端代码file_send.py


#file_send.py
import socket,os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sk = socket.socket()
address = ('127.0.0.1',8001)
sk.connect(address)
filename = input("please input filename:")
path = os.path.join(BASE_DIR,filename)
filesize = os.stat(path).st_size
fileinfo = '%s|%s'%(filename,str(filesize))
sk.sendall(bytes(fileinfo,'utf8'))

f = open(path,'rb')

has_sent = 0
while has_sent != int(filesize):
  data = f.read(1024)
  sk.sendall(data)
  has_sent += len(data)

print('well done!')
f.close()
sk.close()

运行程序后,可将file_send.py中指定的test.png文件成功上传并保存至当前路径下的file_recv文件夹内。

以上是本文的全部内容,希望能为读者的学习提供帮助,欢迎继续支持本站获取更多技术资源。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表