| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- from fastapi import APIRouter, File, UploadFile, Form, BackgroundTasks, Depends
- from fastapi.responses import JSONResponse, FileResponse
- from starlette.websockets import WebSocket
- from app.api import get_current_user, get_current_user_websocket
- from app.models import UserModel
- from app.utils.excelmerge.conformity import run_conformity
- import shutil
- import os
- router = APIRouter()
- ALLOWED_EXTENSIONS = {'xlsx'}
- EXCEL_FILES_PATH = 'data/output'
- SOURCE_FILES_PATH = 'data/source'
- def allowed_file(filename: str) -> bool:
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
- def create_dir_if_not_exists(path: str):
- if not os.path.exists(path):
- os.makedirs(path)
- def clear_directory(path: str) -> dict:
- for filename in os.listdir(path):
- file_path = os.path.join(path, filename)
- try:
- if os.path.isfile(file_path) or os.path.islink(file_path):
- os.unlink(file_path)
- elif os.path.isdir(file_path):
- shutil.rmtree(file_path)
- except Exception as e:
- return {"error": "清空出错"}
- return {"message": "目录已清空"}
- def user_file_path(userid: str, path: str) -> str:
- return os.path.join(path, userid)
- @router.post('/excel/upload')
- async def upload_file(files: list[UploadFile] = File(...), current_user: UserModel = Depends(get_current_user)):
- user_id = str(current_user.id)
- if not any(file.filename for file in files):
- return JSONResponse(content={"error": "没有文件部分"}, status_code=400)
- if not user_id:
- return JSONResponse(content={"error": "缺少参数user_id"}, status_code=400)
- user_source = user_file_path(user_id, SOURCE_FILES_PATH)
- user_excel = EXCEL_FILES_PATH
- create_dir_if_not_exists(user_source)
- create_dir_if_not_exists(user_excel)
- clear_directory(user_source)
- save_path_list = []
- for file in files:
- if file.filename == '':
- return JSONResponse(content={"error": "没有选择文件"}, status_code=400)
- if file and allowed_file(file.filename):
- save_path = os.path.join(user_source, file.filename)
- with open(save_path, 'wb') as buffer:
- shutil.copyfileobj(file.file, buffer)
- save_path_list.append(save_path)
- else:
- return JSONResponse(content={"error": "不允许的文件类型"}, status_code=400)
- return JSONResponse(content={"code": 200, "msg": "", "data": {}}, status_code=200)
- # ws://localhost:9201/api/document/ws/excel
- @router.websocket("/ws/excel")
- async def ws_excel(websocket: WebSocket, current_user: UserModel = Depends(get_current_user_websocket)):
- await websocket.accept()
- user_id = str(current_user.id)
- user_source = user_file_path(user_id, SOURCE_FILES_PATH)
- user_excel = EXCEL_FILES_PATH
- create_dir_if_not_exists(user_source)
- create_dir_if_not_exists(user_excel)
- while True:
- data = await websocket.receive_text()
- try:
- if data == "\"合并Excel\"":
- merge_file = run_conformity(user_source, user_excel)
- if merge_file is not None:
- await websocket.send_json({
- "message": "文档合并成功!",
- "type": "stream",
- "file_name": f"{merge_file}.xlsx",
- "download_url": f"./api/document/download/{merge_file}.xlsx"
- })
- await websocket.send_json({
- "message": "文档合并成功!",
- "type": "close",
- })
- else:
- await websocket.send_json({"error": "合并失败", "type": "stream", "files": []})
- else:
- print(f"Received data: {data}")
- await websocket.send_json({"error": "未知指令", "data": str(data)})
- except Exception as e:
- await websocket.send_json({"error": str(e)})
- await websocket.close()
- @router.get("/download/{file_full_name}")
- async def download_file(background_tasks: BackgroundTasks, file_full_name: str):
- file_name = os.path.basename(file_full_name)
- user_excel = EXCEL_FILES_PATH
- file_path = os.path.join(user_excel, file_full_name)
- if not os.path.exists(file_path):
- return JSONResponse(content={"error": "文件不存在"}, status_code=404)
- def delete_file():
- try:
- os.unlink(file_path)
- except OSError as e:
- print(f"Deleting file error")
- # 待下载完成后删除生成的文件
- background_tasks.add_task(delete_file)
- return FileResponse(path=file_path, filename=file_name,
- media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|