This commit is contained in:
ping 2026-07-17 09:58:17 +08:00
parent 90225fee1c
commit 2d3425c7c1

View File

@ -1,26 +1,39 @@
async def upload_file(ns={}):
import os
import base64
import datetime
async def read_file_bytes(upload_file):
if isinstance(upload_file, bytes):
return upload_file
if isinstance(upload_file, bytearray):
return bytes(upload_file)
if isinstance(upload_file, dict):
upload_file = upload_file.get('file') or upload_file.get('content') or upload_file.get('body')
if hasattr(upload_file, 'file'):
upload_file = upload_file.file
if hasattr(upload_file, 'read'):
file_content = upload_file.read()
if hasattr(file_content, '__await__'):
file_content = await file_content
return file_content
return None
upload_file_data = ns.get('file') or ns.get('upload_file') or ns.get('file_bytes')
file_name = ns.get('file_name')
file_content = ns.get('file_content') or ns.get('file_base64')
storage_type = ns.get('storage_type', 'local')
if not file_name and hasattr(upload_file_data, 'filename'):
file_name = upload_file_data.filename
if not file_name and isinstance(upload_file_data, dict):
file_name = upload_file_data.get('filename') or upload_file_data.get('file_name') or upload_file_data.get('name')
if not file_name:
return {
'status': False,
'msg': '请传递file_name'
}
if not file_content:
if not upload_file_data:
return {
'status': False,
'msg': '请传递file_content'
}
if storage_type != 'local':
return {
'status': False,
'msg': '暂不支持该存储类型'
'msg': '请上传文件'
}
safe_file_name = os.path.basename(file_name).replace('\\', '').replace('/', '')
@ -31,21 +44,24 @@ async def upload_file(ns={}):
}
try:
if ',' in file_content and file_content.split(',', 1)[0].startswith('data:'):
file_content = file_content.split(',', 1)[1]
file_bytes = base64.b64decode(file_content)
file_bytes = await read_file_bytes(upload_file_data)
if not file_bytes:
return {
'status': False,
'msg': '文件内容为空'
}
except Exception as e:
return {
'status': False,
'msg': '文件内容解析失败, %s' % str(e)
'msg': '文件内容读取失败, %s' % str(e)
}
now_date = datetime.datetime.now()
date_path = now_date.strftime('%Y/%m/%d')
relative_path = '%s/%s' % (date_path, safe_file_name)
base_path = '/data'
save_dir = os.path.join(base_path, now_date.strftime('%Y'), now_date.strftime('%m'), now_date.strftime('%d'))
save_path = os.path.join(save_dir, safe_file_name)
file_path = '/data/%s/%s' % (date_path, safe_file_name)
try:
if not os.path.exists(save_dir):
@ -56,9 +72,9 @@ async def upload_file(ns={}):
'status': True,
'msg': 'upload success',
'data': {
'storage_type': storage_type,
'storage_type': 'local',
'file_name': safe_file_name,
'file_path': relative_path,
'file_path': file_path,
'save_path': save_path,
'file_size': len(file_bytes)
}