#!/usr/bin/env python3 # -*- coding: utf-8 -*- from fastapi import APIRouter, Request, Depends, Form, Body, File, UploadFile from database import get_db from utils.StripTagsHTMLParser import * from sqlalchemy.orm import Session from datetime import datetime, timedelta import uuid from passlib.context import CryptContext from models import * from sqlalchemy import text, exists, and_, or_, not_ from sqlalchemy.sql import func from models import * from extensions import logger from utils import * import os from .oauth import valid_access_token import traceback router = APIRouter() @router.post('/uploadfile') async def uploadfile( *, request: Request, certificate_no: str = Body(...), from_type: str = Body(...), file: UploadFile = File(...), client_id = Depends(valid_access_token), db: Session = Depends(get_db) ): try: file_name = file.filename suffix = os.path.splitext(file_name)[-1] new_file_name = get_filename(suffix) file_dir = os.path.join('/data/upload/mergefile/uploads/', "danger") os.makedirs(file_dir, mode=0o764, exist_ok=True) file_path = os.path.abspath("{}/{}".format(file_dir, new_file_name)) if os.path.exists(file_path): os.remove(file_path) content = await file.read() with open(file_path, 'wb') as f: f.write(content) file_id = new_guid() db_entity = DangerUploadFile( id=file_id, certificate_no=certificate_no, file_name=file_name, save_filepath=file_path, file_type=suffix, from_type=from_type, upload_time=datetime.now()) db.add(db_entity) db.commit() return { "code": 1, "msg": "上传成功", "time": unixstamp(), "data": { "id": file_id } } except Exception as e: traceback.print_exc() return { "code": 0, "msg": "上传失败,文件太大", "time": unixstamp(), "data": {} } def get_filename(suffix): return str(uuid.uuid1()) + suffix.lower()