【大文件分片上传】

一、大文件分片上传

1.思想就是将原来的文件分成几个小的文件,然后分别让一个一个小文件独立上传。

2.对于一个文件要计算文件的大小file_size,然后确定分片文件的大小sub_file_size,然后通过: file_size / sub_file_size计算得出分成几个小文件,如果不是整除,分成小文件的个数需要加一,用math.ceil(file_size / sub_file_size)得出的数即可。

3.上代码:

# _*_ encoding:utf-8 _*_
import os
from math import ceil
from a_config import test_para


def sub_file(filename):
    file_list = []

    with open(filename, 'rb') as f1:
        file_size = os.path.getsize(filename)
        print('file_zise: ', file_size)

        file_size_mb = round(float(file_size) / 1024 / 1024, 2)
        print('file_size_mb: ', file_size_mb)

        file_size_int = int(ceil(file_size_mb))
        print('file_size_int: ', file_size_int)

         # read 5mb every time, count_num is indicate how many new sub file
        count_num = ceil(file_size_int / 5)

        seek_index = 0
        for i in range(int(count_num)):
            with open(test_para.abs_path + 'd_src\\sub_file_' + str(i+1), 'wb') as f2:
            	# confirm the seek pointer in the big file
                f1.seek(seek_index)
                # read 5mb data from the big file, then write the new sub file
                f2.write(f1.read(1024*1024*5))
                # seek pointer to the read location
                seek_index = seek_index + 1024*1024*5
                # put the new sub file into file_list
                file_list.append({"file": 'sub_file_' + str(i+1), "number": i+1})

        print('file_list:', file_list)

		# read the new sub file form file_list, then get the size of new sub file
        for i in range(len(file_list)):
            print(file_list[i].get('file'), file_list[i].get('number'), os.path.getsize(test_para.abs_path + "d_src\\" + file_list[i].get('file')))

        return file_list

二、几个小的文件分片合并成大的文件,逆一下就好了

1.将file_list中的文件分片,读取并连续写入到新建的大文件中即可,不上代码了。(注:需要将大文件命名成预期文件的类型)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值