Files
SMANAGE/backup/_api_backup/TempLateAPI/GERP/API/Asset/UploadChunk.api
T

80 lines
2.5 KiB
Plaintext

from PDAPI import *
import os
import json
import hashlib
RESOURCE_ROOT = os.path.join(os.path.abspath(os.path.join(os.getcwd(), "resource")))
TEMP_ROOT = os.path.join(RESOURCE_ROOT, ".tmp")
__metadata__ = {
"methods": ["POST"],
"blueprint": "GERP",
"permission": 3.0,
"attributes": [],
"limit": "120 per minute",
}
def HandleRequest(_CleanedData):
current_user = UGM.GetELTUser()
if not current_user:
return {"code": 401, "msg": "未登录"}, 401
upload_id = flask.request.form.get("uploadId", "").strip()
chunk_index = flask.request.form.get("chunkIndex", "").strip()
chunk_md5 = flask.request.form.get("chunkMD5", "").strip()
if not upload_id or not chunk_index:
return {"code": 1, "msg": "缺少uploadId或chunkIndex"}, 400
try:
chunk_index = int(chunk_index)
except ValueError:
return {"code": 1, "msg": "chunkIndex必须为整数"}, 400
temp_dir = os.path.join(TEMP_ROOT, upload_id)
if not os.path.isdir(temp_dir):
return {"code": 1, "msg": "上传会话不存在或已过期"}, 404
meta_path = os.path.join(temp_dir, "meta.json")
if not os.path.exists(meta_path):
return {"code": 1, "msg": "上传元数据不存在"}, 404
with open(meta_path, "r", encoding="utf-8") as f:
meta = json.load(f)
if chunk_index < 0 or chunk_index >= meta["totalChunks"]:
return {"code": 1, "msg": f"分片索引超出范围(0-{meta['totalChunks']-1})"}, 400
if 'chunk' not in flask.request.files:
return {"code": 1, "msg": "未找到分片数据"}, 400
chunk_file = flask.request.files['chunk']
chunk_data = chunk_file.read()
if chunk_md5:
actual_md5 = hashlib.md5(chunk_data).hexdigest()
if actual_md5 != chunk_md5:
return {"code": 1, "msg": f"分片校验失败: 期望{chunk_md5}, 实际{actual_md5}"}, 400
chunk_path = os.path.join(temp_dir, str(chunk_index))
with open(chunk_path, "wb") as f:
f.write(chunk_data)
if chunk_index not in meta["receivedChunks"]:
meta["receivedChunks"].append(chunk_index)
with open(meta_path, "w", encoding="utf-8") as f:
json.dump(meta, f, ensure_ascii=False)
return {
"code": 0,
"msg": "分片上传成功",
"data": {
"uploadId": upload_id,
"chunkIndex": chunk_index,
"chunkSize": len(chunk_data),
"receivedChunks": sorted(meta["receivedChunks"]),
"totalChunks": meta["totalChunks"],
}
}, 200