文件名上传修复

This commit is contained in:
朱潮 2026-03-02 14:27:32 +08:00
parent 55505c727a
commit 82ffe8b623

View File

@ -164,7 +164,7 @@ async def list_files(path: str = "", recursive: bool = False):
async def upload_file(file: UploadFile = File(...), path: str = Form("")): async def upload_file(file: UploadFile = File(...), path: str = Form("")):
""" """
上传文件 上传文件
Args: Args:
file: 上传的文件 file: 上传的文件
path: 目标路径相对于支持目录 path: 目标路径相对于支持目录
@ -174,26 +174,29 @@ async def upload_file(file: UploadFile = File(...), path: str = Form("")):
if not target_path.exists() or not target_path.is_dir(): if not target_path.exists() or not target_path.is_dir():
target_path = resolve_path("projects") target_path = resolve_path("projects")
target_path.mkdir(parents=True, exist_ok=True) target_path.mkdir(parents=True, exist_ok=True)
file_path = target_path / file.filename # 将文件名中的空格替换为下划线
safe_filename = file.filename.replace(" ", "_") if file.filename else file.filename
file_path = target_path / safe_filename
# 如果文件已存在,检查是否覆盖 # 如果文件已存在,检查是否覆盖
if file_path.exists(): if file_path.exists():
# 可以添加版本控制或重命名逻辑 # 可以添加版本控制或重命名逻辑
pass pass
with open(file_path, "wb") as buffer: with open(file_path, "wb") as buffer:
content = await file.read() content = await file.read()
buffer.write(content) buffer.write(content)
return { return {
"success": True, "success": True,
"message": "文件上传成功", "message": "文件上传成功",
"filename": file.filename, "filename": safe_filename,
"path": str(Path(path) / file.filename), "original_filename": file.filename,
"path": str(Path(path) / safe_filename),
"size": len(content) "size": len(content)
} }
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}") raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")