文件上传
模块位置
| 组件 | 位置 |
|---|---|
| 路由 | internal/platform/file/router.go |
| Handler | internal/platform/file/handler/file_handler.go |
| 存储抽象 | pkg/storage/ |
存储实现
| 类型 | 文件 | 说明 |
|---|---|---|
| 本地存储 | pkg/storage/local.go | 本地文件系统 |
| 阿里云 OSS | pkg/storage/aliyun.go | 阿里云对象存储 |
接口说明
上传文件
请求:
POST /api/v1/files
Content-Type: multipart/form-data参数:
| 参数 | 类型 | 说明 |
|---|---|---|
| file | file | 上传的文件 |
响应:
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 实现 |
