代码拉取完成,页面将自动刷新
# app.py
import os
from fastapi import FastAPI, File, UploadFile, HTTPException, Response,Form
from fastapi.responses import StreamingResponse
import shutil
app = FastAPI()
@app.post("/upload/")
async def upload_file(
file: UploadFile = File(...),
custom_param: str = Form(...)
):
folder = "uploads/"
file_content = await file.read()
filename = os.path.join(folder, file.filename)
os.makedirs(folder, exist_ok=True)
with open(filename, "wb") as f:
f.write(file_content)
return {"filename": file.filename, "custom_param": custom_param, "message": "File uploaded successfully!"}
@app.get("/download/{filename}")
async def download_file(filename: str):
folder = "uploads/"
filepath = os.path.join(folder, filename)
if not os.path.exists(filepath):
raise HTTPException(status_code=404, detail="File not found")
with open(filepath, "rb") as f:
content = f.read()
return Response(content=content, media_type="application/octet-stream")
@app.get("/download/stream/{filename}")
async def download_file_stream(filename: str):
folder = "uploads/"
filepath = os.path.join(folder, filename)
if not os.path.exists(filepath):
raise HTTPException(status_code=404, detail="File not found")
return StreamingResponse(open(filepath, "rb"), media_type="application/octet-stream")
@app.get("/exists/{filename}")
async def file_exists(filename: str):
folder = "uploads/"
filepath = os.path.join(folder, filename)
return {"exists": os.path.exists(filepath)}
@app.delete("/delete/{filename}")
async def delete_file(filename: str):
folder = "uploads/"
filepath = os.path.join(folder, filename)
target_folder = 'deleted'
if os.path.exists(filepath):
os.makedirs(target_folder, exist_ok=True)
target_filepath = os.path.join(target_folder, filename)
shutil.move(filepath, target_filepath)
return {"message": f"File {filename} deleted successfully."}
else:
raise HTTPException(status_code=404, detail="File not found")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。