python--简单的文件断点续传实例
一、程序说明

1、文件上传目标路径:home/file
2、目标文件:putfile.png
3、服务端代码:put_server.py
4、客户端代码:put_client.py
二、各部分代码
1、服务端代码:put_server.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
实现文件断点续传的服务器端
""" import socket
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) home = os.path.join(BASE_DIR, "home/file")
sk = socket.socket()
sk.bind(('127.0.0.1', 8001))
sk.listen(5) while True:
print("Waiting....")
conn, addr = sk.accept()
conn.sendall(bytes('欢迎登录', encoding='utf-8'))
flag = True
while flag:
client_bytes = conn.recv(1024) #接收客户端发送过来的内容
client_str = str(client_bytes, encoding='utf-8') #将内容转换成字符串 # 将客户端发送过来的内容以"|"拆分为:命名方法,文件名,文件大小,目标路径
func, file_name, file_byte_size, targe_path = client_str.split('|', 3)
file_byte_size = int(file_byte_size)
path = os.path.join(home, file_name)
has_received = 0 #首先判断该路径下是否已存在文件
if os.path.exists(path):
conn.sendall(bytes("", encoding='utf-8')) #发送通知客户端,该文件已存在
is_continue = str(conn.recv(1024), encoding='utf-8') #等待客户端选择回复
if is_continue == "":
has_file_size = os.stat(path).st_size
conn.sendall(bytes(str(has_file_size), encoding='utf-8')) #将已接收的文件大小给客户端
has_received += has_file_size
f = open(path, 'ab')
else:
f = open(path, 'wb')
else:
conn.sendall(bytes("", encoding='utf-8'))
f = open(path, 'wb') while has_received < file_byte_size:
try:
data = conn.recv(1024)
if not data:
raise Exception
except Exception:
flag = False
break
f.write(data)
has_received += len(data)
print("文件已接收完成!")
f.close()
2、客户端代码:put_client.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
实现文件断点续传的客户端
""" import socket
import sys
import re
import os
FILE_DIR = os.path.dirname(__file__) ck = socket.socket()
ck.connect(('127.0.0.1', 8001))
print(str(ck.recv(1024), encoding='utf-8')) #定义一个函数,计算进度条
def bar(num = 1, sum = 100):
rate = float(num) / float(sum)
rate_num = int(rate * 100)
temp = '\r%d %%' % (rate_num)
sys.stdout.write(temp) while True:
inp = input('请输入(内容格式:post|文件路径 目标路径): \n >>> ').strip() #输入内容格式:命令|文件路径 目标路径
func, file_path =inp.split("|", 1) #将输入的内容拆分为两部分,方法名和路径
local_path, target_path = re.split("\s*", file_path, 1) #再将路径部分,通过正则表达式。以空格拆分为:文件路径和上传的目标路径
file_byte_size = os.stat(local_path).st_size #获取文件的大小
file_name = os.path.basename(local_path) #设置文件名 post_info = "post|%s|%s|%s" % (file_name, file_byte_size, target_path) #将发送的内容进行拼接
ck.sendall(bytes(post_info, encoding='utf-8')) #向服务器端发送内容 result_exist = str(ck.recv(1024), encoding='utf-8')
has_sent = 0
if result_exist == "":
inp = input("文件已存在,是否续传?Y/N:").strip()
if inp.upper() == 'Y':
ck.sendall(bytes("", encoding='utf-8'))
result_continue_pos = str(ck.recv(1024), encoding='utf-8') #已经传输了多少的文件内容
print(result_continue_pos)
has_sent = int(result_continue_pos) else:
ck.sendall(bytes("", encoding='utf-8')) #发送2005代表不续传 file_obj = open(local_path, 'rb') #对文件进行读操作
file_obj.seek(has_sent) #调整指针 while has_sent < file_byte_size:
data = file_obj.read(1024)
ck.sendall(data)
has_sent += len(data)
bar(has_sent, file_byte_size) #进度条 file_obj.close()
print("文件上传成功!")
python--简单的文件断点续传实例的更多相关文章
- Python读写Excel文件的实例
最近由于经常要用到Excel,需要根据Excel表格中的内容对一些apk进行处理,手动处理很麻烦,于是决定写脚本来处理.首先贴出网上找来的读写Excel的脚本. 1.读取Excel(需要安装xlrd) ...
- python 简单实现文件拷贝
1.背景 一日加班需要写一个文件拷贝的函数. 写了几版拷贝函数,有需要的直接粘贴过去 def CopyLocaleFile1(sorfile,desfile): #第一版 sorfp=open(sor ...
- Python 简单的文件上传功能
简单地在程序当前目录下上传一张图片: 1.png 到程序的 yuan 文件夹下.这里使用的是固定参数 post,如果后期有需求,可以增加判断来更加完善程序. # server 端 import soc ...
- C#中简单的文件操作实例
using System; using System.IO; namespace Demo { class Program { static string tmpPath = @"D:/Lg ...
- Python 简单批量请求接口实例
#coding:utf-8 ''' Created on 2017年11月10日 @author: li.liu ''' import urllib import time str1=''' http ...
- 【python-ini】python读写ini文件
[python-ini]python读写ini文件 本文实例讲述了Python读写ini文件的方法.分享给大家供大家参考.具体如下: 比如有一个文件update.ini,里面有这些内容: 1 2 ...
- python操作xml文件
一.什么是xml? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. abc.xml <?xml version="1.0&q ...
- 服务器文档下载zip格式 SQL Server SQL分页查询 C#过滤html标签 EF 延时加载与死锁 在JS方法中返回多个值的三种方法(转载) IEnumerable,ICollection,IList接口问题 不吹不擂,你想要的Python面试都在这里了【315+道题】 基于mvc三层架构和ajax技术实现最简单的文件上传 事件管理
服务器文档下载zip格式 刚好这次项目中遇到了这个东西,就来弄一下,挺简单的,但是前台调用的时候弄错了,浪费了大半天的时间,本人也是菜鸟一枚.开始吧.(MVC的) @using Rattan.Co ...
- Python绘制PDF文件~超简单的小程序
Python绘制PDF文件 项目简介 这次项目很简单,本次项目课,代码不超过40行,主要是使用 urllib和reportlab模块,来生成一个pdf文件. reportlab官方文档 http:// ...
随机推荐
- Spring BeanFactory继承结构图
结构图 高清大图:https://img2018.cnblogs.com/blog/813478/201910/813478-20191030114422275-1092084932.jpg 源文件( ...
- VisualSVN 新版本终于支持一个解决方案下多workcopy了,并解决了上个版本一个重要BUG
Multiple working copies within a single solution VisualSVN 7.0 and older require the solution file a ...
- Nginx Tutorial #1: Basic Concepts(转)
add by zhj: 文章写的很好,适合初学者 原文:https://www.netguru.com/codestories/nginx-tutorial-basics-concepts Intro ...
- Java并发编程: CountDownLatch、CyclicBarrier和 Semaphore
java 1.5提供了一些非常有用的辅助类来帮助并发编程,比如CountDownLatch,CyclicBarrier和Semaphore. 1.CountDownLatch –主线程阻塞等待,最后完 ...
- MQTT v5.0------SUBSCRIBE 报文
SUBSCRIBE 报文 固定报头: 剩余长度字段 表示可变报头的长度加上有效载荷的长度,被编码为变长字节整数. 可变报头 SUBSCRIBE报文可变报头按顺序包含以下字段:报文标识符(Packet ...
- 关于使用mySqlSugar插入数据异常解决方案
项目的解决方案中引用的有mysqlsugar的数据库操作库,在使用插入数据过程中一些特殊的生僻字或表情符号总会提示: Incorrect string value: '\xF0\x9F...' for ...
- MVC拦截
1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Web; 5using Syst ...
- GIt 错误与常用命令
命令和一些其他的属性等 *)在使用git commit -m “description" 这个描述会加在上次提交后所有add的文件后面,所以也可能产生不符合这个描述的文件后面也跟了这个描述, ...
- 学习笔记之Django
The Web framework for perfectionists with deadlines | Django https://www.djangoproject.com/ Django m ...
- JavaScript 之 Array 对象
Array 对象 之前已经了解了 Array(数组)的定义和基本操作.数组的基本操作. 下面来学习更多的方法. 检测一个对象是否是数组 instanceof // 看看该变量是否是该对象的实例 Arr ...