【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,"分块不完整"
posted @ 2024-01-18 11:00  PythonNew_Mr.Wang  Views(45)  Comments(0Edit  收藏  举报