async def upload_file(ns={}): import os 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') 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 upload_file_data: return { 'status': False, 'msg': '请上传文件' } safe_file_name = os.path.basename(file_name).replace('\\', '').replace('/', '') if not safe_file_name: return { 'status': False, 'msg': 'file_name错误' } try: 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) } now_date = datetime.datetime.now() date_path = now_date.strftime('%Y/%m/%d') 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): os.makedirs(save_dir) with open(save_path, 'wb') as f: f.write(file_bytes) return { 'status': True, 'msg': 'upload success', 'data': { 'storage_type': 'local', 'file_name': safe_file_name, 'file_path': file_path, 'save_path': save_path, 'file_size': len(file_bytes) } } except Exception as e: return { 'status': False, 'msg': '文件保存失败, %s' % str(e) } ret = await upload_file(params_kw) return ret