Skip to content

Instantly share code, notes, and snippets.

@hikariyo
Last active October 16, 2023 02:56
Show Gist options
  • Save hikariyo/cc4b53e49ec5ff7f020037514ddd74a9 to your computer and use it in GitHub Desktop.
Save hikariyo/cc4b53e49ec5ff7f020037514ddd74a9 to your computer and use it in GitHub Desktop.
Image hosting server for PicGo with web-uploader plugin
from typing import Annotated
from pathlib import Path, PurePosixPath
from datetime import datetime
from fastapi import FastAPI, UploadFile, Header, Response
from urllib.parse import urljoin
PREFIX_URL = 'https://example.com/'
ROOT_PATH = Path(__file__).parent / 'data'
TOKEN = 'YOUR_TOKEN'
app = FastAPI()
@app.post("/upload")
async def receive_upload_file(img: UploadFile, authorization: Annotated[str | None, Header()] = None):
if authorization != TOKEN:
return Response(status_code=401)
date = datetime.now()
path = ROOT_PATH / str(date.year) / f'{date.month:02d}' / img.filename
path.parent.mkdir(exist_ok=True, parents=True)
path.write_bytes(await img.read())
url_path = str(PurePosixPath(path.relative_to(ROOT_PATH)))
return {'url': urljoin(PREFIX_URL, url_path)}
@app.delete("/delete/{path:path}")
async def delete_upload_file(path: str, authorization: Annotated[str | None, Header()] = None):
if authorization != TOKEN:
return Response(status_code=401)
fp = ROOT_PATH / path
if not fp.exists():
return {'success': False, 'msg': 'File Not Found'}
fp.unlink()
return {'success': True, 'msg': f'Deleted {path}'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment