files.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """
  2. encoding: UTF-8
  3. @author:clx
  4. @file:files.py.py
  5. @time:2023/5/30 6:08
  6. """
  7. import json
  8. import os
  9. import random
  10. import time
  11. import re
  12. import aiofiles
  13. from fastapi import APIRouter, File, UploadFile, Request, Response, status, HTTPException
  14. from fastapi.responses import FileResponse, StreamingResponse
  15. from typing import Annotated, List
  16. from minio import Minio
  17. from io import BytesIO
  18. from config import config
  19. """
  20. minio_client = Minio(
  21. "127.0.0.1:9000",
  22. access_key="minioadmin",
  23. secret_key="minioadmin",
  24. secure=False
  25. )
  26. """
  27. # 创建minio对象
  28. minio_class = config.MinioOperate()
  29. # 连接minio
  30. minio_client = minio_class.link_minio()
  31. # 创建bucket
  32. minio_class.create_bucket()
  33. router = APIRouter()
  34. # minio ?上传文件时在重复时,需要修改文件名
  35. @router.post("/file")
  36. async def create_file(file: UploadFile = File(...)):
  37. timestamp = str(time.time())
  38. uid = re.sub(r"\.", "", timestamp)
  39. front, ext = os.path.splitext(file.filename)
  40. file_name = uid + ext # 168549427474778.png
  41. data = await file.read()
  42. file_stream = BytesIO(initial_bytes=data)
  43. size = len(data)
  44. uri = os.path.join("/file/", file_name)
  45. if (minio_client.put_object(
  46. "file1",
  47. file_name,
  48. file_stream,
  49. size
  50. )):
  51. return {"status": 200, "path": uri}
  52. else:
  53. return {"msg": "上传失败", "status": 400}
  54. # 图片预览
  55. # response = StreamingResponse(file_content,media_type='image/jpg)
  56. # 图片下载功能
  57. @router.get("/file/{uid}")
  58. async def download_file(uid: str):
  59. try:
  60. file_obj = minio_client.get_object("file1", uid)
  61. file_content = BytesIO(file_obj.read())
  62. # response = StreamingResponse(file_content,
  63. # media_type='application/octet-stream',
  64. # headers={"Content-Disposition": f"attachment; filename={uid}"})
  65. response = StreamingResponse(file_content, media_type='image/png')
  66. except Exception as e:
  67. return {"error": str(e)}
  68. return response
  69. # 删除
  70. @router.delete("/file/{uid}")
  71. async def delete_file(uid: str):
  72. try:
  73. minio_client.get_object("file1", uid)
  74. minio_client.remove_object("file1", uid)
  75. return {"msg": "删除图片成功!", "status": 200}
  76. except:
  77. return {"msg": "Not Found", "status": 404}