from fastapi import HTTPException import re import os import logging import shutil from app.tools.doc2docx import doc2docx # # word上传格式要求 # ALLOWED_EXTENSIONS_DOC = { # 'application/msword', # 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' # } # # # excel上传格式要求 # ALLOWED_EXTENSIONS_EXCEL = { # 'application/vnd.ms-excel', # 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # } # 获取日志记录器 logger = logging.getLogger(__name__) # 验证上传的文件是否符合要求 def verification_files(file, UPLOAD_DIR, file_type, exception_type): try: # 检查文件类型 if file.content_type not in file_type: raise HTTPException(status_code=400, detail="文件类型不支持") # 判断各个文件名是否符合该上传需求 # 如果文件名与实际需要的文件不匹配,则抛出异常 if not re.search(file.filename[3:11], exception_type): raise HTTPException(status_code=400, detail=f"请传入{exception_type}") # 先判断文件是否已经上传,如果已经上传,则删除旧的,保存新的 # 保存文件到对应的位置,判断是否已经存在相关文件,如果有,则删除旧的 if os.path.exists(UPLOAD_DIR) and len(os.listdir(UPLOAD_DIR)) > 0: for file_name in os.listdir(UPLOAD_DIR): if re.search(file_name[3:11], exception_type): os.remove(os.path.join(UPLOAD_DIR, file_name)) logger.info(f"删除旧文件{file_name}") # 不管是不是有文件,都走这一步 logger.info(f"开始上传{exception_type}") # 如果文件夹不存在,则新建 if not os.path.exists(UPLOAD_DIR): os.makedirs(UPLOAD_DIR) file_path = os.path.join(UPLOAD_DIR, file.filename) with open(file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) # 如果上传为doc,需要转成docx if file_path.endswith(".doc"): doc2docx(file_path) logger.info(f"文件{file.filename}格式转换为docx成功") # elif file_path.endswith('.xls'): # # xls2xlsx(file_path) # logger.info(f'文件{file.filename}格式转换为xlsx成功') except Exception as e: logger.error(f"文档格式校验失败:{e}") raise HTTPException(status_code=500, detail=f"文档格式校验失败{e}")