Skip to content

图片上传接口

类说明

Upload 类提供图片上传功能,支持 JPG、PNG、GIF、WebP 格式,单个文件最大5MB。

安全特性:

  • 双重MIME类型验证(finfo + mime_content_type)
  • 图片魔数验证(getimagesize)
  • WordPress自动文件重命名防止覆盖
  • 每日上传数量限制(500张/天)

使用说明:

  • 需要登录才能使用
  • 使用 FormData 格式上传
  • 字段名为 image

上传图片

Method : POST

URL : /wp-json/vtheme/v1/upload/image

Auth required : True

Headers :

  • Authorization: Bearer

Form Data :

  • image : [file] 图片文件 (JPG/PNG/GIF/WebP, 最大5MB)

Success Response

Code : 200 OK

Content example :

json
{
  "success": true,
  "url": "http://example.com/wp-content/uploads/2023/01/image.jpg",
  "file": "/var/www/html/wp-content/uploads/2023/01/image.jpg",
  "attachment_id": 123
}

返回字段说明:

  • url : 图片访问URL
  • file : 服务器文件路径
  • attachment_id : WordPress媒体库附件ID(可用于设置特色图片等)

Error Response

Code : 400 Bad Request

Content examples :

json
{
  "code": "no_file",
  "message": "没有接收到文件",
  "data": {
    "status": 400
  }
}
json
{
  "code": "invalid_type",
  "message": "文件类型不匹配或不受支持",
  "data": {
    "status": 400
  }
}
json
{
  "code": "invalid_image",
  "message": "无效的图片文件",
  "data": {
    "status": 400
  }
}
json
{
  "code": "file_too_large",
  "message": "文件大小不能超过5MB",
  "data": {
    "status": 400
  }
}
json
{
  "code": "upload_limit",
  "message": "今日上传图片数量已达上限(50张)",
  "data": {
    "status": 400
  }
}

Code : 401 Unauthorized

Content example :

json
{
  "code": "unauthorized",
  "message": "用户未登录",
  "data": {
    "status": 401
  }
}

Code : 500 Internal Server Error

Content example :

json
{
  "code": "upload_failed",
  "message": "文件上传失败:具体错误信息",
  "data": {
    "status": 500
  }
}

使用示例

JavaScript Fetch API

javascript
// 获取文件
const fileInput = document.querySelector('#image-input');
const file = fileInput.files[0];

// 构建FormData
const formData = new FormData();
formData.append('image', file);

// 发送请求
fetch('/wp-json/vtheme/v1/upload/image', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ' + token
  },
  body: formData
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    console.log('上传成功:', data.url);
    console.log('附件ID:', data.attachment_id);
  } else {
    console.error('上传失败:', data.message);
  }
})
.catch(error => {
  console.error('请求错误:', error);
});

注意事项

  1. 文件格式限制:只支持 JPG、PNG、GIF、WebP 格式
  2. 文件大小限制:单个文件不超过5MB
  3. 每日限额:每个用户每天最多上传500张图片
  4. 安全性:系统会进行多重验证确保文件安全性
  5. 返回值使用
    • url 用于显示图片
    • attachment_id 可用于设置文章特色图片或其他需要媒体库ID的场景