main #138
73
b/docs/upload_file.dspy
Normal file
73
b/docs/upload_file.dspy
Normal file
@ -0,0 +1,73 @@
|
||||
async def upload_file(ns={}):
|
||||
import os
|
||||
import base64
|
||||
import datetime
|
||||
|
||||
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:
|
||||
return {
|
||||
'status': False,
|
||||
'msg': '请传递file_name'
|
||||
}
|
||||
if not file_content:
|
||||
return {
|
||||
'status': False,
|
||||
'msg': '请传递file_content'
|
||||
}
|
||||
if storage_type != 'local':
|
||||
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:
|
||||
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)
|
||||
except Exception as e:
|
||||
return {
|
||||
'status': False,
|
||||
'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)
|
||||
|
||||
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': storage_type,
|
||||
'file_name': safe_file_name,
|
||||
'file_path': relative_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
|
||||
Loading…
x
Reference in New Issue
Block a user