From 419744686f9c97de8b4b749a531c1065eb920c34 Mon Sep 17 00:00:00 2001 From: jingrow Date: Fri, 21 Nov 2025 01:44:02 +0800 Subject: [PATCH] =?UTF-8?q?feat(jfile):=20=E6=B7=BB=E5=8A=A0CORS=E5=93=8D?= =?UTF-8?q?=E5=BA=94=E5=A4=B4=E6=94=AF=E6=8C=81=E7=AC=AC=E4=B8=89=E6=96=B9?= =?UTF-8?q?=E5=89=8D=E7=AB=AF=E4=B8=8B=E8=BD=BD=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加HTTP中间件为/files路径响应添加CORS响应头 - 支持Access-Control-Allow-Origin、Access-Control-Allow-Methods和Access-Control-Expose-Headers - 添加Content-Disposition头让浏览器直接下载而不是打开图片 - 统一处理OPTIONS预检请求 - 优化性能:提前返回非目标请求 --- apps/jfile/app.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/apps/jfile/app.py b/apps/jfile/app.py index fcf79e3..052dd83 100644 --- a/apps/jfile/app.py +++ b/apps/jfile/app.py @@ -1,9 +1,11 @@ import uvicorn -from fastapi import FastAPI +from fastapi import FastAPI, Request from fastapi.staticfiles import StaticFiles +from fastapi.responses import Response from file_cleaner import FileCleaner from settings import settings import asyncio +import os app = FastAPI( title="www", @@ -11,6 +13,39 @@ app = FastAPI( version="1.0.0" ) +# 添加中间件,为静态文件响应添加 CORS 响应头和下载头 +@app.middleware("http") +async def add_cors_headers(request: Request, call_next): + # 只处理 /files 路径的请求,提前返回提高效率 + if not request.url.path.startswith("/files"): + return await call_next(request) + + # 处理 OPTIONS 预检请求 + if request.method == "OPTIONS": + return Response( + headers={ + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, OPTIONS", + "Access-Control-Expose-Headers": "Content-Disposition" + } + ) + + # 处理 GET 请求 + response = await call_next(request) + + # 添加 CORS 响应头 + response.headers["Access-Control-Allow-Origin"] = "*" + response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS" + response.headers["Access-Control-Expose-Headers"] = "Content-Disposition" + + # 添加 Content-Disposition 头,让浏览器下载而不是打开 + if "Content-Disposition" not in response.headers: + filename = os.path.basename(request.url.path) + if filename: + response.headers["Content-Disposition"] = f'attachment; filename="{filename}"' + + return response + # 挂载静态文件目录 app.mount("/files", StaticFiles(directory="files"), name="files")