Skip to content

文件上传

模块位置

组件位置
路由internal/platform/file/router.go
Handlerinternal/platform/file/handler/file_handler.go
存储抽象pkg/storage/

存储实现

类型文件说明
本地存储pkg/storage/local.go本地文件系统
阿里云 OSSpkg/storage/aliyun.go阿里云对象存储

接口说明

上传文件

请求

POST /api/v1/files
Content-Type: multipart/form-data

参数

参数类型说明
filefile上传的文件

响应

json
{
  "code": "00000",
  "msg": "操作成功",
  "data": {
    "url": "http://example.com/files/2024/01/15/xxx.jpg",
    "name": "xxx.jpg",
    "size": 1024
  }
}

存储配置

本地存储

yaml
storage:
  type: local
  local:
    path: ./uploads        # 存储路径
    urlPrefix: /files      # URL 前缀

阿里云 OSS

yaml
storage:
  type: aliyun
  aliyun:
    endpoint: oss-cn-hangzhou.aliyuncs.com
    accessKeyId: your-access-key-id
    accessKeySecret: your-access-key-secret
    bucketName: your-bucket
    urlPrefix: https://your-bucket.oss-cn-hangzhou.aliyuncs.com

使用示例

客户端上传

bash
curl -X POST http://localhost:8000/api/v1/files \
  -H "Authorization: Bearer {token}" \
  -F "file=@/path/to/image.jpg"

前端上传

javascript
const formData = new FormData()
formData.append('file', file)

const response = await fetch('/api/v1/files', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`
  },
  body: formData
})

const result = await response.json()
console.log(result.data.url)

文件限制

配置项默认值说明
最大文件大小10MB单文件最大大小
允许类型image/*, .pdf, .doc允许的文件类型

相关文件

文件说明
internal/platform/file/router.go路由定义
internal/platform/file/handler/file_handler.go文件处理 Handler
pkg/storage/local.go本地存储实现
pkg/storage/aliyun.go阿里云 OSS 实现

基于 MIT 许可发布