分段上传_客户端测试

1. 需求

把一个zip包分段上传到服务器上。

 

2. 测试

// 改造而来,非原创
import
os import requests import math import traceback from requests_toolbelt.multipart.encoder import MultipartEncoder URL = "xxx" def _slice( file_path, offset, size, file_name, file_total_size): try: targetFile = open(file_path, 'rb') targetFile.seek(offset) m = MultipartEncoder( fields={ 'file': (file_name, targetFile.read(size), 'application/octet-stream')             } ) targetFile.close() headers = {"Content-Type": m.content_type, "range": "{0}-{1}/{2}".format(offset, offset + size-1, file_total_size) } response = requests.post(url=url,headers=headers, data=m) print(response.content) print(response)
status = 0
except Exception as e: traceback.print_exc() status = 1   finally:      return status def do_upload(file_path): file_total_size = os.path.getsize(file_path) chunk_size = 500 chunks = math.ceil(file_total_size / chunk_size) file_path = file_path.replace('\\', '/') file_names = file_path.split('/') file_name = file_names[-1] for i in range(chunks): if i + 1 == chunks: current_size = file_total_size % chunk_size else: current_size = chunk_size _slice(file_path, i * chunk_size, current_size, file_name, file_total_size) if __name__ == "__main__": do_upload('xx.zip')

 

posted @ 2021-09-29 15:19  fly_pig  阅读(40)  评论(0编辑  收藏  举报