生成一段断点续传代码
时间: 2024-11-07 07:12:55 浏览: 14
JAVA多线程与线程安全实践-基于Http协议的断点续传【毕业论文】.zip
断点续传(Resumable Upload)是一种在网络上传文件时常用的策略,当网络连接中断后,可以从上次断开的地方继续上传,而不是从头开始。这通常通过将大文件分割成小块,在服务器端保存进度信息来实现。下面是一个简单的Python示例,使用requests库模拟HTTP请求的断点续传功能:
```python
import requests
from io import BytesIO
import os
# 文件路径和大小
file_path = 'path_to_your_file'
file_size = os.path.getsize(file_path)
# 每次上传的小块大小
chunk_size = 1024 * 1024 # 1MB
def upload_chunk(start, end):
with open(file_path, 'rb') as file:
file.seek(start)
chunk = file.read(end - start)
response = requests.put('http://your-server/upload', data=chunk, headers={'Range': f'bytes={start}-{end-1}'})
return response.status_code
# 定义总块数和已上传的块索引
total_chunks = file_size // chunk_size + (file_size % chunk_size > 0)
uploaded_chunks = 0
while uploaded_chunks < total_chunks:
try:
# 开始位置
start = uploaded_chunks * chunk_size
# 如果文件剩余部分小于一块大小,则读取完整块
if file_size - start < chunk_size:
end = file_size
else:
end = start + chunk_size
status_code = upload_chunk(start, end)
if status_code == 200 or status_code == 206: # 表示成功或部分成功
uploaded_chunks += 1
else:
print(f"Upload failed with status code {status_code}")
break
except Exception as e:
print(f"Error occurred: {e}")
# 记录失败的位置并重新开始从那里继续
os.system(f'touch {file_path}.upload_inprogress')
start = os.path.getsize(file_path) - chunk_size
continue
if uploaded_chunks == total_chunks:
print("File upload completed successfully.")
```
阅读全文