12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- import os
- import re
- import time
- from datetime import datetime, timedelta
- from io import BytesIO
- from fastapi import Depends, FastAPI, HTTPException, status, UploadFile, APIRouter, File
- from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
- from starlette.responses import StreamingResponse
- from config import config
- from models.model import *
- from utils.jwt import authenticate_user, ACCESS_TOKEN_EXPIRE_MINUTES, create_access_token, get_current_active_user
- # 创建minio对象
- minio_class = config.MinioOperate()
- # 连接minio
- minio_client = minio_class.link_minio()
- # 创建bucket
- minio_class.create_bucket()
- router = APIRouter()
- @router.post("/token", response_model=Token)
- async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
- user = authenticate_user(fake_users_db, form_data.username, form_data.password)
- if not user:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Incorrect username or password",
- headers={"WWW-Authenticate": "Bearer"},
- )
- access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
- access_token = create_access_token(
- data={"sub": user.username}, expires_delta=access_token_expires
- )
- return {"access_token": access_token, "token_type": "bearer"}
- # minio ?上传文件时在重复时,需要修改文件名
- @router.post("/file")
- async def create_file(file: UploadFile = File(...),current_user: User = Depends(get_current_active_user)):
- timestamp = str(time.time())
- uid = re.sub(r"\.", "", timestamp)
- front, ext = os.path.splitext(file.filename)
- file_name = uid + ext # 168549427474778.png
- data = await file.read()
- file_stream = BytesIO(initial_bytes=data)
- size = len(data)
- uri = os.path.join("/file/", file_name)
- if (minio_client.put_object(
- "file1",
- file_name,
- file_stream,
- size
- )):
- return {"status": 200, "path": uri}
- else:
- return {"msg": "上传失败", "status": 400}
- # 图片预览
- # response = StreamingResponse(file_content,media_type='image/jpg)
- # 图片下载功能
- @router.get("/file/{uid}")
- async def download_file(uid: str):
- try:
- file_obj = minio_client.get_object("file1", uid)
- file_content = BytesIO(file_obj.read())
- # response = StreamingResponse(file_content,
- # media_type='application/octet-stream',
- # headers={"Content-Disposition": f"attachment; filename={uid}"})
- response = StreamingResponse(file_content, media_type='image/png')
- except Exception as e:
- return {"error": str(e)}
- return response
- # 删除
- @router.delete("/file/{uid}")
- async def delete_file(uid: str,current_user: User = Depends(get_current_active_user)):
- try:
- minio_client.get_object("file1", uid)
- minio_client.remove_object("file1", uid)
- return {"msg": "删除图片成功!", "status": 200}
- except:
- return {"msg": "Not Found", "status": 404}
|