|
|
@@ -0,0 +1,61 @@
|
|
|
+import os
|
|
|
+from fastapi import APIRouter, UploadFile, File, HTTPException
|
|
|
+from typing import List
|
|
|
+from app.core.config import settings
|
|
|
+from app.utils.file_ops import save_upload_file, delete_file
|
|
|
+
|
|
|
+router = APIRouter()
|
|
|
+
|
|
|
+
|
|
|
+@router.post("/upload", summary="上传图片 (Multipart)")
|
|
|
+async def upload_image(file: UploadFile = File(...)):
|
|
|
+ """
|
|
|
+ 接收文件上传,保存并返回可访问的 URL。
|
|
|
+ 树莓派调用此接口。
|
|
|
+ """
|
|
|
+ if not file.content_type.startswith("image/"):
|
|
|
+ raise HTTPException(status_code=400, detail="File must be an image")
|
|
|
+
|
|
|
+ try:
|
|
|
+ # 保存文件
|
|
|
+ filename = await save_upload_file(file)
|
|
|
+
|
|
|
+ # 拼接完整的 URL 地址
|
|
|
+ file_url = f"{settings.BASE_URL}/static/{filename}"
|
|
|
+
|
|
|
+ return {
|
|
|
+ "status": "success",
|
|
|
+ "filename": filename,
|
|
|
+ "url": file_url
|
|
|
+ }
|
|
|
+ except Exception as e:
|
|
|
+ raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
|
|
|
+
|
|
|
+
|
|
|
+# --- 赠送的实用接口 ---
|
|
|
+
|
|
|
+@router.get("/images", summary="列出所有已上传图片")
|
|
|
+async def list_images():
|
|
|
+ """查看服务器上现在存了哪些图片 (调试用)"""
|
|
|
+ if not os.path.exists(settings.UPLOAD_PATH):
|
|
|
+ return []
|
|
|
+
|
|
|
+ files = sorted(os.listdir(settings.UPLOAD_PATH), reverse=True) # 按时间倒序(假设文件名带时间戳)
|
|
|
+
|
|
|
+ image_list = []
|
|
|
+ for f in files:
|
|
|
+ if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
|
|
|
+ image_list.append({
|
|
|
+ "filename": f,
|
|
|
+ "url": f"{settings.BASE_URL}/static/{f}"
|
|
|
+ })
|
|
|
+ return image_list
|
|
|
+
|
|
|
+
|
|
|
+@router.delete("/images/{filename}", summary="删除指定图片")
|
|
|
+async def delete_image(filename: str):
|
|
|
+ """清理图片"""
|
|
|
+ success = delete_file(filename)
|
|
|
+ if not success:
|
|
|
+ raise HTTPException(status_code=404, detail="File not found")
|
|
|
+ return {"status": "deleted", "filename": filename}
|