一、大文件分片上传
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中的文件分片,读取并连续写入到新建的大文件中即可,不上代码了。(注:需要将大文件命名成预期文件的类型)