@@ -409,6 +409,34 @@ async def _mkdir_p(self, directory_path: str):
409
409
detail = f"目录创建失败: { content [:200 ]} " ,
410
410
)
411
411
412
+ async def _is_dir_empty (self , dir_path : str ) -> bool :
413
+ """检查目录是否为空"""
414
+ url = self ._build_url (dir_path )
415
+
416
+ async with aiohttp .ClientSession (auth = self .auth ) as session :
417
+ async with session .request ("PROPFIND" , url , headers = {"Depth" : "1" }) as resp :
418
+ if resp .status != 207 : # 207 是 Multi-Status 响应
419
+ return False
420
+ content = await resp .text ()
421
+ # 如果只有一个 response(当前目录),说明目录为空
422
+ return content .count ("<D:response>" ) <= 1
423
+
424
+ async def _delete_empty_dirs (self , file_path : str , session : aiohttp .ClientSession ):
425
+ """递归删除空目录"""
426
+ path_obj = Path (file_path )
427
+ current_path = path_obj .parent
428
+
429
+ while str (current_path ) != "." :
430
+ if not await self ._is_dir_empty (str (current_path )):
431
+ break
432
+
433
+ url = self ._build_url (str (current_path ))
434
+ async with session .delete (url ) as resp :
435
+ if resp .status not in (200 , 204 , 404 ):
436
+ break
437
+
438
+ current_path = current_path .parent
439
+
412
440
async def save_file (self , file : UploadFile , save_path : str ):
413
441
"""保存文件(自动创建目录)"""
414
442
# 分离文件名和目录路径
@@ -437,19 +465,24 @@ async def save_file(self, file: UploadFile, save_path: str):
437
465
raise HTTPException (status_code = 503 , detail = f"WebDAV连接异常: { str (e )} " )
438
466
439
467
async def delete_file (self , file_code : FileCodes ):
440
- """删除WebDAV文件 """
468
+ """删除WebDAV文件及空目录 """
441
469
file_path = await file_code .get_file_path ()
442
470
url = self ._build_url (file_path )
443
471
444
472
try :
445
473
async with aiohttp .ClientSession (auth = self .auth ) as session :
474
+ # 删除文件
446
475
async with session .delete (url ) as resp :
447
- if resp .status not in (200 , 204 ):
476
+ if resp .status not in (200 , 204 , 404 ):
448
477
content = await resp .text ()
449
478
raise HTTPException (
450
479
status_code = resp .status ,
451
480
detail = f"WebDAV删除失败: { content [:200 ]} " ,
452
481
)
482
+
483
+ # 使用同一个 session 删除空目录
484
+ await self ._delete_empty_dirs (file_path , session )
485
+
453
486
except aiohttp .ClientError as e :
454
487
raise HTTPException (status_code = 503 , detail = f"WebDAV连接异常: { str (e )} " )
455
488
0 commit comments