CloudFlare ImgBed

repository·main·Indexed 26 days ago

https://github.com/marseventh/cloudflare-imgbed

A self-hosted file and image hosting solution supporting storage backends including Cloudflare R2, S3, and Telegram. It provides a web interface and programmatic access via RESTful API and WebDAV. The project supports both serverless deployment via Cloudflare Workers and Docker-based deployment using a native Node.js server with Hono, simulating Cloudflare Pages Functions with SQLite and local storage.

Tokens
2.7K
Snippets
1
Records
16
Agent score
92%

What's inside cloudflare-imgbed

  1. Overview of CloudFlare ImgBed

    main

    CloudFlare ImgBed is an open-source file hosting and image bed solution that supports both Docker and Serverless deployment. It allows you to unify multiple storage backends into a single management interface.

    Supported Storage Channels:

    • Telegram
    • Discord
    • Cloudflare R2
    • S3 compatible storage
    • Hugging Face
    • WebDAV

    Key Features:

    • File management and directory organization
    • Identity authentication and user management
    • Content auditing
    • RESTful API support
    • WebDAV support
    • Suitable for personal image hosting, website resource management, and lightweight file distribution.
  2. Explore the CloudFlare ImgBed Ecosystem

    main

    The project supports an ecosystem of community-driven tools and integrations:

    • Plugin Extensions: Browser extensions, integrations for Typecho, WordPress, and Obsidian, and OpenList drivers.
    • Companion Applications: Desktop clients and bot tools.
    • AI Agent Applications: Official project skills and related tools.
    • Tutorials and Guides: Community-created videos and articles.

    Developers can contribute to the ecosystem by submitting work via the Ecosystem Call for Contributions.

  3. Deploy cloudflare-imgbed using Docker Compose

    main

    You can deploy the cloudflare-imgbed service using Docker Compose. The service maps the internal port 8080 to host port 7658 and persists data in a local ./data directory.

    version: '3.8'
    
    services:
      imgbed:
        image: marseventh/cloudflare-imgbed:latest
        ports:
          - "7658:8080"
        volumes:
          - ./data:/app/data
        restart: unless-stopped
  4. Perform chunked uploads for large files

    main

    For large files that exceed standard upload limits, use the chunked upload workflow by passing specific query parameters to the upload endpoint:

    1. Initialize: Call the endpoint with ?initChunked=true to start a session.
    2. Upload Chunks: Upload individual parts using ?chunked=true.
    3. Merge: Once all parts are uploaded, call the endpoint with ?chunked=true&merge=true to combine the chunks into a single file.
    4. Cleanup: If an upload is interrupted, use ?cleanup=true&uploadId={id}&totalChunks={count} to clean up orphaned chunks.
  5. Generate Cloudflare Worker routes

    main

    The Cloudflare Worker deployment entrypoint is automatically generated to map incoming requests to the appropriate business logic modules. To regenerate this file after making changes to the functions/ directory, run the following command:

    node deploy/worker/generate-routes.js

    Warning: Do not edit deploy/worker/index.js manually, as your changes will be overwritten by the generation command.

  6. Understand the Function routing and middleware simulation

    main

    The server simulates Cloudflare Pages Functions by routing specific path prefixes to files in the functions/ directory.

    Supported Path Prefixes:

    • /api/
    • /upload
    • /file/
    • /dav/
    • /random

    Routing Logic:

    1. Exact Match: Looks for functions/{path}.js.
    2. Index Match: Looks for functions/{path}/index.js.
    3. Wildcard Match: Looks for functions/{path}/[[path]].js (matches from deepest to shallowest).

    Middleware Support: The server searches for _middleware.js files in the root functions/ directory and in each directory level corresponding to the request path. It builds a middleware chain that is executed before the main handler.

    Function Handler Signature: Functions are expected to export an onRequest function (or method-specific handlers like onRequestGet, onRequestPost, etc.). The context object provided to these functions includes:

    • request: The standard Web Request object.
    • env: An object containing process.env, img_d1 (SQLite instance), img_r2 (Local R2 instance), and IMAGE_PROCESSOR.
    • params: URL parameters extracted from the path (e.g., from [[path]].js).
    • waitUntil(promise): A function to handle asynchronous tasks after the response is sent.
    • next(): A function to move to the next middleware/handler in the chain.
  7. Run the project in Docker mode using Native Node.js

    main

    The project includes a native Node.js server implementation designed for Docker environments. This server uses Hono as the web framework to proxy Cloudflare Pages Functions requests. It replaces Cloudflare-specific services with local alternatives:

    • Database: Uses SqliteD1 (SQLite) instead of Cloudflare D1.
    • Storage: Uses LocalR2Storage (local file system) instead of Cloudflare R2.
    • Functions: Proxies requests to the functions/ directory, simulating the Cloudflare Pages Functions runtime.

    The server listens on the port specified by the PORT environment variable (defaults to 8080).

  8. Configure the Docker-mode environment variables

    main

    When running the native Node.js server, the following environment variables and behaviors are used:

    • PORT: The port the server will listen on (default: 8080).
    • Automatic Data Directory: The server automatically creates a data/ directory in the project root to store the SQLite database and R2 local storage files.
    • Simulated Cloudflare API: The server injects a mock globalThis.caches object to prevent errors in code expecting the Cloudflare Cache API.
    • IP Address Handling: The server attempts to extract the client's real IP using @hono/node-server/conninfo and injects it into the x-real-ip header to simulate Cloudflare's cf-connecting-ip behavior.
  9. Configure Random Image API settings

    main

    The Random Image API behavior is controlled via the othersConfig fetched from the environment. To enable or restrict the API, you must configure the following keys in your system configuration:

    • randomImageAPI.enabled: Boolean. Set to true to allow access to the random endpoint.
    • randomImageAPI.allowedDir: Comma-separated string of directory paths. The dir parameter in the request must match one of these paths or be a subdirectory of one.
  10. Upload files via the API endpoint

    main

    The /functions/upload/index.js endpoint handles file uploads to various storage channels. It supports standard multipart/form-data uploads and chunked uploads for large files.

    Supported Upload Channels

    You can specify the target storage channel using the uploadChannel query parameter:

    • telegram (Default)
    • cfr2 (Cloudflare R2)
    • s3 (Amazon S3 or S3-compatible)
    • discord (Discord via Bot)
    • huggingface (HuggingFace Repositories)
    • webdav (WebDAV servers)
    • external (Direct URL upload)

    Query Parameters

    ParameterTypeDescription
    uploadChannelstringThe storage provider to use (e.g., telegram, s3, discord).
    channelNamestringOptional. Specifies a specific configured channel name within a provider.
    uploadFolderstringOptional. The target directory path. Sanitized to prevent path traversal.
    returnFormatstringdefault (returns /file/id) or full (returns absolute URL).
    chunkedbooleanSet to true to initiate chunked upload logic.
    mergebooleanSet to true to merge existing chunks.
    initChunkedbooleanSet to true to initialize a new chunked upload session.
    cleanupbooleanSet to true to trigger a cleanup request (requires uploadId and totalChunks).
    autoRetrybooleanSet to false to disable automatic channel switching on upload failure.
    serverCompressbooleanSet to false to bypass server-side compression (useful for Telegram).
    sha256stringOptional. Precomputed SHA256 hash for HuggingFace uploads.
    urlstringRequired if uploadChannel=external. The URL of the file to upload.
  11. Retrieve Bing wallpapers via onRequest API

    main

    The onRequest function serves as an API endpoint to fetch the latest Bing wallpapers. It fetches data from the Bing Image Archive and returns a JSON response containing an array of image objects.

    Response Format: Returns a JSON object with the following structure:

    • status (boolean): Indicates if the operation was successful.
    • message (string): A status message (e.g., "操作成功").
    • data (array): An array of image objects retrieved from Bing.