files.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import os
  2. import re
  3. import time
  4. from datetime import datetime, timedelta
  5. from io import BytesIO
  6. from fastapi import Depends, FastAPI, HTTPException, status, UploadFile, APIRouter, File
  7. from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
  8. from starlette.responses import StreamingResponse
  9. from config import config
  10. from models.model import *
  11. from utils.jwt import authenticate_user, ACCESS_TOKEN_EXPIRE_MINUTES, create_access_token, get_current_active_user
  12. # 创建minio对象
  13. minio_class = config.MinioOperate()
  14. # 连接minio
  15. minio_client = minio_class.link_minio()
  16. # 创建bucket
  17. minio_class.create_bucket()
  18. router = APIRouter()
  19. @router.post("/token", response_model=Token)
  20. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  21. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  22. if not user:
  23. raise HTTPException(
  24. status_code=status.HTTP_401_UNAUTHORIZED,
  25. detail="Incorrect username or password",
  26. headers={"WWW-Authenticate": "Bearer"},
  27. )
  28. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  29. access_token = create_access_token(
  30. data={"sub": user.username}, expires_delta=access_token_expires
  31. )
  32. return {"access_token": access_token, "token_type": "bearer"}
  33. # minio ?上传文件时在重复时,需要修改文件名
  34. @router.post("/file")
  35. async def create_file(file: UploadFile = File(...),current_user: User = Depends(get_current_active_user)):
  36. timestamp = str(time.time())
  37. uid = re.sub(r"\.", "", timestamp)
  38. front, ext = os.path.splitext(file.filename)
  39. file_name = uid + ext # 168549427474778.png
  40. data = await file.read()
  41. file_stream = BytesIO(initial_bytes=data)
  42. size = len(data)
  43. uri = os.path.join("/file/", file_name)
  44. if (minio_client.put_object(
  45. "file1",
  46. file_name,
  47. file_stream,
  48. size
  49. )):
  50. return {"status": 200, "path": uri}
  51. else:
  52. return {"msg": "上传失败", "status": 400}
  53. # 图片预览
  54. # response = StreamingResponse(file_content,media_type='image/jpg)
  55. # 图片下载功能
  56. @router.get("/file/{uid}")
  57. async def download_file(uid: str):
  58. try:
  59. file_obj = minio_client.get_object("file1", uid)
  60. file_content = BytesIO(file_obj.read())
  61. # response = StreamingResponse(file_content,
  62. # media_type='application/octet-stream',
  63. # headers={"Content-Disposition": f"attachment; filename={uid}"})
  64. response = StreamingResponse(file_content, media_type='image/png')
  65. except Exception as e:
  66. return {"error": str(e)}
  67. return response
  68. # 删除
  69. @router.delete("/file/{uid}")
  70. async def delete_file(uid: str,current_user: User = Depends(get_current_active_user)):
  71. try:
  72. minio_client.get_object("file1", uid)
  73. minio_client.remove_object("file1", uid)
  74. return {"msg": "删除图片成功!", "status": 200}
  75. except:
  76. return {"msg": "Not Found", "status": 404}