n/cnu/heiyu · 2 个月前
注册 登录
n/cn · 2 个月前 · 189 次浏览
u/heiyu🌩钻石

一个简单TG图床系统,搓导航时无聊产物

[login]
image
image

有后台管理,登录后台能删除图片,还还API功能,随便找个AI搓一下整合到自己的站点上也不错

全是AI搓的也别嫌弃,测试几天还不错

本想部署在CF上的好像不能长久保存图片,就改了,改好后发现部署在CF上好像也长久保存图片哈哈哈

ImgTG — Telegram 图床系统

基于 Telegram 私有频道的图床服务,支持 API Key 认证,可对接任何网站/APP 上传图片。

架构

用户/APP ──[API+Key]──→ 后端 ──[上传]──→ Telegram 私有频道(永久存储)
                              │
浏览器 ──[访问图片]──→ 后端 ──[代理]──→ Telegram CDN
  • 存储:Telegram 私有频道,Telegram 永久免费保存
  • 访问:后端反向代理 Telegram 文件,对外返回可访问 URL
  • 认证:API Key(X-API-Key 头 或 ?key= 参数),第三方拿 Key 即可上传

一、部署说明

1. 准备工作

事项 操作
Telegram Bot 找 @BotFather 创建 Bot,获取 Token
私有频道 创建私有频道,把 Bot 添加为频道管理员
频道 ID 用 @userinfobot 查询频道 ID(格式 -100xxxxxxxxxx)

2. 安装

# 克隆/上传代码到服务器
cd /www/Node/tgimg
npm install

3. 配置 .env

cp .env.example .env
TG_BOT_TOKEN=123456:ABC-DEF...           # Bot Token
TG_CHAT_ID=-1001234567890                # 私有频道 ID
BASIC_USER=admin                         # 管理后台账号
BASIC_PASS=你的管理密码                   # 管理后台密码
PORT=25741                               # 后端监听端口(用高端口,避免 root 权限)
BASE_URL=https://img.05.si               # 对外访问域名(必须填,同域免 Key 判断依赖它)
SSL_KEY_PATH=                            # 留空=HTTP 模式(用 CF 做 HTTPS)
SSL_CERT_PATH=

BASE_URL 必须正确填写:反代后后端收到的 host 头是内网地址,同域免 Key 判断会用到 BASE_URL 的域名。

4. 启动

node server.js
# 或用 PM2 守护
pm2 start server.js --name imgtg
pm2 save

5. 反向代理配置(宝塔面板 + Cloudflare)

三层架构(关键:各司其职,不循环):

浏览器(HTTPS) → CF 边缘(Always Use HTTPS) → 服务器:80(HTTP) → 宝塔反代 → 127.0.0.1:25741(HTTP) → 后端

Cloudflare 控制台

设置项 值
DNS A 记录 img → 服务器 IP,橙色云朵(代理开启)
SSL/TLS 加密模式选 Flexible
Always Use HTTPS 开(HTTP→HTTPS 重定向在 CF 边缘做)

宝塔面板

操作 说明
添加网站 img.05.si 绑定域名
反向代理 目标 http://127.0.0.1:25741
强制 HTTPS 必须关掉 ← 最关键的一步

为什么必须关掉宝塔的「强制HTTPS」:宝塔在反代层做 HTTP→HTTPS 重定向,和反代本身冲突会导致 Too many redirects 无限循环。HTTPS 重定向上移到 CF 边缘(Always Use HTTPS)即可,宝塔只做纯反代。

6. 验证

# 能打开上传页面 = 部署成功
curl http://img.05.si/

访问 https://img.05.si/admin 输入 BASIC_USER / BASIC_PASS 进入管理后台,可管理 API Key 和图片。


二、API 调用说明

基础信息

项目 值
上传地址 https://img.05.si/upload 或 https://img.05.si/api/upload
图片访问 https://img.05.si/image/{id}(公开,无需 Key)
认证方式 X-API-Key 请求头 或 ?key= URL 参数
同域免 Key 从 img.05.si 自身页面上传无需 Key(基于 BASE_URL 域名判断)

1. 上传图片

请求:

POST /upload
Content-Type: multipart/form-data
X-API-Key: sk-xxxxxxxxxxxx
参数 类型 说明
file File 图片/视频文件(JPG/PNG/GIF/WebP/SVG/BMP/MP4/WebM,最大 50MB)

响应:

{
  "success": true,
  "image_id": "a1b2c3d4e5f6",
  "url": "https://img.05.si/image/a1b2c3d4e5f6",
  "is_video": false,
  "markdown": "![image](https://img.05.si/image/a1b2c3d4e5f6)",
  "html": "<img src=\"https://img.05.si/image/a1b2c3d4e5f6\" alt=\"image\">",
  "bbcode": "[img]https://img.05.si/image/a1b2c3d4e5f6[/img]"
}

错误:

状态码 说明
403 API Key 无效或未提供
400 未上传文件
413 文件超过 50MB
500 上传失败(Telegram API 错误)

2. 访问图片(公开)

GET /image/{id}

直接返回图片二进制,可直接用于 <img src>。无需 API Key。

3. 各语言调用示例

cURL

curl -X POST https://img.05.si/upload \
  -H "X-API-Key: sk-xxxxxxxxxxxx" \
  -F "file=@/path/to/image.jpg"

JavaScript(浏览器 / fetch)

async function uploadImage(file) {
  const formData = new FormData();
  formData.append('file', file);

  const res = await fetch('https://img.05.si/upload', {
    method: 'POST',
    headers: { 'X-API-Key': 'sk-xxxxxxxxxxxx' },
    body: formData,
  });

  const data = await res.json();
  if (data.success) {
    return data.url;  // https://img.05.si/image/xxxx
  }
  throw new Error(data.error);
}

JavaScript(XHR 带进度)

function uploadImage(file, onProgress) {
  return new Promise((resolve, reject) => {
    const fd = new FormData();
    fd.append('file', file);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://img.05.si/upload');
    xhr.setRequestHeader('X-API-Key', 'sk-xxxxxxxxxxxx');
    xhr.upload.onprogress = e => {
      if (e.lengthComputable && onProgress) {
        onProgress(Math.round(e.loaded / e.total * 100));
      }
    };
    xhr.onload = () => {
      const d = JSON.parse(xhr.responseText);
      d.success ? resolve(d.url) : reject(new Error(d.error));
    };
    xhr.onerror = () => reject(new Error('Network error'));
    xhr.send(fd);
  });
}

Python

import requests

def upload_image(file_path, api_key='sk-xxxxxxxxxxxx'):
    with open(file_path, 'rb') as f:
        res = requests.post(
            'https://img.05.si/upload',
            headers={'X-API-Key': api_key},
            files={'file': f}
        )
    data = res.json()
    if data['success']:
        return data['url']
    raise Exception(data['error'])

PHP

function uploadImage($filePath, $apiKey = 'sk-xxxxxxxxxxxx') {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://img.05.si/upload',
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ["X-API-Key: $apiKey"],
        CURLOPT_POSTFIELDS => ['file' => new CURLFile($filePath)],
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($res, true);
    return $data['success'] ? $data['url'] : throw new Exception($data['error']);
}

Java

import java.io.*;
import java.net.*;

public class ImgTG {
    public static String upload(File file, String apiKey) throws Exception {
        String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
        HttpURLConnection conn = (HttpURLConnection)
            new URL("https://img.05.si/upload").openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("X-API-Key", apiKey);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (OutputStream os = conn.getOutputStream()) {
            os.write(("--" + boundary + "\r\n").getBytes());
            os.write("Content-Disposition: form-data; name=\"file\"; filename=\""
                + file.getName() + "\"\r\n\r\n".getBytes());
            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buf = new byte[4096]; int n;
                while ((n = fis.read(buf)) > 0) os.write(buf, 0, n);
            }
            os.write(("\r\n--" + boundary + "--\r\n").getBytes());
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream()))) {
            String line = br.readLine(); // 返回 JSON,解析取 url
            return line; // 实际用 Gson/Jackson 解析
        }
    }
}

HTML 表单(最简单)

<form action="https://img.05.si/upload" method="post" enctype="multipart/form-data">
  <input type="hidden" name="key" value="sk-xxxxxxxxxxxx">
  <input type="file" name="file">
  <button type="submit">上传</button>
</form>

4. API Key 管理

在 https://img.05.si/admin 管理后台用 Basic Auth(BASIC_USER/BASIC_PASS)登录后:

操作 接口
创建 Key POST /api/keys body {"name":"备注"} → 返回 sk-xxx
列出 Key GET /api/keys
删除 Key DELETE /api/keys/{key}
列出图片 GET /api/images
删除图片 DELETE /api/delete/{id}

三、常见问题

Q1: 上传报 Too many redirects

根因:宝塔面板开了「强制HTTPS」,和反代冲突导致循环。
解决:宝塔面板 → SSL → 关掉强制HTTPS,改用 Cloudflare 的 Always Use HTTPS。

Q2: 自己网页上传报 Invalid API key

根因:.env 里 BASE_URL 没填或填错,同域免 Key 判断失效。
解决:确保 BASE_URL=https://你的域名。

Q3: 其他网站上传报 Invalid API key

这是正常的。其他网站必须带 API Key:

headers: { 'X-API-Key': 'sk-xxxxxxxxxxxx' }
// 或
fetch('https://img.05.si/upload?key=sk-xxxxxxxxxxxx', ...)

Q4: 端口 80 报 EACCES: permission denied

根因:Linux 非 root 用户不能绑 1024 以下端口。
解决:.env 用 PORT=25741 等高端口,通过宝塔反代 80→25741。

Q5: 图片访问 404

图片 URL 格式:https://img.05.si/image/{id},{id} 是上传返回的 image_id。确认 ID 正确且数据库 data/db.json 未被误删。

tgimg.zip|attachment (1.1 MB)

[/login]

3
17
登录后参与讨论。

17 条回复

排序
  1. heyuxuanyyds1 钻石 3 YEARS 2 个月前

    我其实也写过一个tg图床系统的文章,只不过存储方式更丰富

    0
  2. xiaoyi669 💬 钻石 钻石会员 2 个月前

    快快分享出来 😋

    2
  3. heyuxuanyyds1 钻石 3 YEARS 2 个月前

    你看我主页,那个“如何获得一个图床(建站三件套第三套)”就是我写的(也可以直接搜)

    0
  4. xiaoyi669 💬 钻石 钻石会员 2 个月前

    ok

    1
  5. 继续这个对话 →
  6. heiyu 🌩 钻石 楼主 2 YEARS 2 个月前

    分享出来玩玩

    1
  7. heyuxuanyyds1 钻石 3 YEARS 2 个月前

    搜“如何获得一个图床(建站三件套第三套)”然后点我的那篇文章即可

    0
  8. Peach_lu 青铜 2 个月前

    其实github也有个类似的项目 如果要部署玩玩的话 也可以了解下 CloudFlare-ImgBed通过cf白嫖

    0
  9. heiyu 🌩 钻石 楼主 2 YEARS 2 个月前

    多是多,主要是自己添加了API,没事整合到自己的网站上不就是省去一个图床了。

    0
  10. syan 💬 黄金 2 个月前

    太厉害了

    0