API使用文档

Endpoint: hostimg.jeffweb.net

注意: 本页面由大语言模型基于原始文档生成。可能不够准确。您可参考原始文档 (请拉到最底下)。

创建API密钥

步骤:

  1. 登录你的账户
  2. 点击"API管理"按钮
  3. 点击"创建新密钥"
  4. 保存显示的AppKey和AppSecret
注意: 每个账户最多可以创建3组密钥。

cURL示例

基本上传

Bash
curl -X POST \
  -F "method=upload" \
  -F "appkey=1234567890123456-abcdefgh" \
  -F "secret=abcdefghijklmnopqrstuvwxyz123456" \
  -F "file=@/path/to/image.jpg" \
  https://hostimg.jeffweb.net/api/api_upload.php

批量上传脚本

Bash
#!/bin/bash

APPKEY="1234567890123456-abcdefgh"
SECRET="abcdefghijklmnopqrstuvwxyz123456"
API_URL="https://hostimg.jeffweb.net/api/api_upload.php"

# 上传单个文件
upload_file() {
    local file=$1
    echo "上传: $file"

    response=$(curl -s -X POST \
        -F "method=upload" \
        -F "appkey=$APPKEY" \
        -F "secret=$SECRET" \
        -F "file=@$file" \
        "$API_URL")

    echo "响应: $response"
    echo "---"
}

# 批量上传目录中的所有图片
for file in *.{jpg,jpeg,png,gif,webp}; do
    if [ -f "$file" ]; then
        upload_file "$file"
    fi
done

Python示例

简单上传

Python
import requests

def upload_image(file_path, appkey, secret):
    """上传图片到图床"""

    url = "https://hostimg.jeffweb.net/api/api_upload.php"

    # 准备数据
    data = {
        'method': 'upload',
        'appkey': appkey,
        'secret': secret
    }

    # 打开文件
    with open(file_path, 'rb') as f:
        files = {'file': f}

        # 发送请求
        response = requests.post(url, data=data, files=files)

        # 返回结果
        return response.json()

# 使用示例
if __name__ == "__main__":
    APPKEY = "1234567890123456-abcdefgh"
    SECRET = "abcdefghijklmnopqrstuvwxyz123456"

    result = upload_image("image.jpg", APPKEY, SECRET)

    if result['success']:
        print(f"上传成功!")
        print(f"URL: {result['url']}")
        print(f"文件ID: {result['file_id']}")
    else:
        print(f"上传失败: {result['message']}")

批量上传类

Python
import os
import requests
from pathlib import Path

class ImageUploader:
    """图床上传工具类"""

    def __init__(self, appkey, secret, api_url=None):
        self.appkey = appkey
        self.secret = secret
        self.api_url = api_url or "https://hostimg.jeffweb.net/api/api_upload.php"
        self.session = requests.Session()

    def upload(self, file_path):
        """上传单个文件"""

        if not os.path.exists(file_path):
            return {'success': False, 'message': '文件不存在'}

        # 检查文件大小
        file_size = os.path.getsize(file_path)
        if file_size > 3 * 1024 * 1024:  # 3MB
            return {'success': False, 'message': '文件大小超过3MB'}

        data = {
            'method': 'upload',
            'appkey': self.appkey,
            'secret': self.secret
        }

        try:
            with open(file_path, 'rb') as f:
                files = {'file': f}
                response = self.session.post(self.api_url, data=data, files=files)
                return response.json()
        except Exception as e:
            return {'success': False, 'message': str(e)}

    def upload_directory(self, directory, extensions=None):
        """批量上传目录中的所有图片"""

        if extensions is None:
            extensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']

        results = []
        path = Path(directory)

        for file_path in path.iterdir():
            if file_path.is_file() and file_path.suffix.lower() in extensions:
                print(f"上传: {file_path.name}")
                result = self.upload(str(file_path))
                results.append({
                    'filename': file_path.name,
                    'result': result
                })

        return results

# 使用示例
if __name__ == "__main__":
    uploader = ImageUploader(
        appkey="1234567890123456-abcdefgh",
        secret="abcdefghijklmnopqrstuvwxyz123456"
    )

    # 上传单个文件
    result = uploader.upload("image.jpg")
    print(result)

    # 批量上传
    results = uploader.upload_directory("./images")
    for item in results:
        print(f"{item['filename']}: {item['result']}")

PHP示例

简单上传

PHP
<?php

function uploadImage($filePath, $appKey, $appSecret) {
    $apiUrl = "https://hostimg.jeffweb.net/api/api_upload.php";

    // 检查文件是否存在
    if (!file_exists($filePath)) {
        return ['success' => false, 'message' => '文件不存在'];
    }

    // 准备POST数据
    $postData = [
        'method' => 'upload',
        'appkey' => $appKey,
        'secret' => $appSecret,
        'file' => new CURLFile($filePath)
    ];

    // 发送请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200) {
        return json_decode($response, true);
    } else {
        return ['success' => false, 'message' => 'HTTP错误: ' . $httpCode];
    }
}

// 使用示例
$appKey = "1234567890123456-abcdefgh";
$appSecret = "abcdefghijklmnopqrstuvwxyz123456";

$result = uploadImage("image.jpg", $appKey, $appSecret);

if ($result['success']) {
    echo "上传成功!\n";
    echo "URL: " . $result['url'] . "\n";
    echo "文件ID: " . $result['file_id'] . "\n";
} else {
    echo "上传失败: " . $result['message'] . "\n";
}
?>

批量上传类

PHP
<?php

class ImageUploader {
    private $appKey;
    private $appSecret;
    private $apiUrl;

    public function __construct($appKey, $appSecret, $apiUrl = null) {
        $this->appKey = $appKey;
        $this->appSecret = $appSecret;
        $this->apiUrl = $apiUrl ?: "https://hostimg.jeffweb.net/api/api_upload.php";
    }

    public function upload($filePath) {
        if (!file_exists($filePath)) {
            return ['success' => false, 'message' => '文件不存在'];
        }

        // 检查文件大小
        $fileSize = filesize($filePath);
        if ($fileSize > 3 * 1024 * 1024) {
            return ['success' => false, 'message' => '文件大小超过3MB'];
        }

        $postData = [
            'method' => 'upload',
            'appkey' => $this->appKey,
            'secret' => $this->appSecret,
            'file' => new CURLFile($filePath)
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response, true);
    }

    public function uploadDirectory($directory, $extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp']) {
        $results = [];

        $files = glob($directory . '/*');
        foreach ($files as $file) {
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));

            if (in_array($ext, $extensions)) {
                echo "上传: " . basename($file) . "\n";
                $result = $this->upload($file);
                $results[] = [
                    'filename' => basename($file),
                    'result' => $result
                ];
            }
        }

        return $results;
    }
}

// 使用示例
$uploader = new ImageUploader(
    "1234567890123456-abcdefgh",
    "abcdefghijklmnopqrstuvwxyz123456"
);

// 上传单个文件
$result = $uploader->upload("image.jpg");
print_r($result);

// 批量上传
$results = $uploader->uploadDirectory("./images");
foreach ($results as $item) {
    echo $item['filename'] . ": ";
    print_r($item['result']);
}
?>

JavaScript示例

浏览器中使用

JavaScript
async function uploadImage(file, appKey, appSecret) {
    const formData = new FormData();
    formData.append('method', 'upload');
    formData.append('appkey', appKey);
    formData.append('secret', appSecret);
    formData.append('file', file);

    try {
        const response = await fetch('https://hostimg.jeffweb.net/api/api_upload.php', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();
        return result;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

// 使用示例
document.getElementById('fileInput').addEventListener('change', async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const appKey = "1234567890123456-abcdefgh";
    const appSecret = "abcdefghijklmnopqrstuvwxyz123456";

    const result = await uploadImage(file, appKey, appSecret);

    if (result.success) {
        console.log('上传成功!');
        console.log('URL:', result.url);
        console.log('文件ID:', result.file_id);
    } else {
        console.error('上传失败:', result.message);
    }
});

Node.js使用

JavaScript
const fs = require('fs');
const FormData = require('form-data');
const axios = require('axios');

async function uploadImage(filePath, appKey, appSecret) {
    const form = new FormData();
    form.append('method', 'upload');
    form.append('appkey', appKey);
    form.append('secret', appSecret);
    form.append('file', fs.createReadStream(filePath));

    try {
        const response = await axios.post(
            'https://hostimg.jeffweb.net/api/api_upload.php',
            form,
            {
                headers: form.getHeaders()
            }
        );

        return response.data;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

// 使用示例
(async () => {
    const appKey = "1234567890123456-abcdefgh";
    const appSecret = "abcdefghijklmnopqrstuvwxyz123456";

    const result = await uploadImage('image.jpg', appKey, appSecret);

    if (result.success) {
        console.log('上传成功!');
        console.log('URL:', result.url);
        console.log('文件ID:', result.file_id);
    } else {
        console.error('上传失败:', result.message);
    }
})();

响应格式

成功响应
JSON
{
    "success": true,
    "message": "上传成功",
    "url": "https://image-hosting-user-content.myownsite.cc/1234567890123456/2026/01/10/abc123.webp",
    "file_id": "abc123"
}
失败响应
JSON
{
    "success": false,
    "message": "无效的AppKey"
}

可能的错误消息

限制说明

限制项 说明
文件大小 最大3MB
文件格式 支持 JPG, PNG, GIF, WebP
每日限额 80张 (与网页上传共享)
转换格式 所有图片会被转换为WebP格式(有损压缩)
并发限制 建议不要同时上传超过10个文件

最佳实践

  1. 错误处理: 始终检查响应中的 success 字段
  2. 文件验证: 上传前检查文件大小和格式
  3. 重试机制: 网络错误时可以实现重试
  4. 保存URL: 上传成功后立即保存返回的URL
  5. 密钥安全: 不要在客户端代码中暴露AppSecret
提示: 需要更多帮助?请参考 README.md 文档。