【Django】通用分块上传
通用分块上传文件
import os
# 通用路径分块上传
def piecemeal_public_load(path, original_md5_hash, chunk_index, upload_file, chunk_total, file_Name):
"""
path: 存放路径(media/后面跟的路径)
original_md5_hash: 临时文件夹名称
chunk_index: 分块索引
upload_file: 二进制文件对象
chunk_total: 分块总数量
file_Name: 合并后的文件名称
:return 布尔值,相对路径
"""
# 创建文件夹
joined_path = os.path.join(settings.MEDIA_ROOT, path)
output_dir = os.path.normpath(joined_path)
os.makedirs(output_dir, exist_ok=True)
# 创建模块临时目录
temp_dir = os.path.join(settings.MEDIA_ROOT, 'temp', original_md5_hash)
os.makedirs(temp_dir, exist_ok=True)
# 保存文件分块到临时目录
chunk_path = os.path.join(temp_dir, f'{chunk_index}_{upload_file.name}')
with open(chunk_path, 'wb+') as destination:
for chunk in upload_file.chunks():
destination.write(chunk)
# 核对分块数量
received_num_chunks = len(os.listdir(temp_dir))
if received_num_chunks == chunk_total:
# 按照索引顺序拼接分块文件
from urllib.parse import unquote
output_path = os.path.join(output_dir, unquote(file_Name))
with open(output_path, 'wb+') as output_file:
for i in range(chunk_total):
chunk_filename = f'{i + 1}_{upload_file.name}'
chunk_path = os.path.join(temp_dir, chunk_filename)
with open(chunk_path, 'rb') as chunk_file:
output_file.write(chunk_file.read())
# 删除已合并的分块文件
os.remove(chunk_path)
# 获取相对路径
relative_path = "media/" + os.path.relpath(output_dir, settings.MEDIA_ROOT)
return True, os.path.normpath(relative_path)
else:
return False,"分块不完整"
Python全栈(后端、数据分析、脚本、爬虫、EXE客户端) / 前端(WEB,移动,H5) / Linux / SpringBoot / 机器学习
分类:
Django
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix