安装了FastAPI 和 Uvicorn:pip install fastapi uvicorn
然后运行代码
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# 假设 dir_upload 为 "/Users/yourusername/yourprojectpath/files/"
dir_upload = "/Users/xiaokkk/Desktop/abragent_v1/files"
# 将文件目录映射为静态文件路径
app.mount("/files", StaticFiles(directory=dir_upload), name="files")
# 示例路由,演示访问文件
@app.get("/")
async def read_root():
return {"message": "你可以在 /files 下访问文件"}
# 示例路由,读取文件内容
@app.get("/read-file/{file_path:path}")
async def read_file(file_path: str):
# 组合完整文件路径
full_path = f"{dir_upload}/{file_path}"
try:
# 读取并返回文件内容
with open(full_path, "r") as file:
file_content = file.read()
return {"file_content": file_content}
except FileNotFoundError:
return {"detail": "文件未找到"}
接下来,在终端运行以下命令启动 FastAPI:
uvicorn main:app --reload
然后,打开浏览器访问 http://127.0.0.1:8000/files/example.txt,应该能够看到 example.txt
文件的内容。同样,你可以根据实际情况修改路径和路由。