文件上传
模块位置
| 组件 | 位置 |
|---|---|
| 路由 | internal/file/router.go |
| Handler | internal/file/handler/file_handler.go |
| 存储抽象 | internal/common/storage/ |
存储实现
| 类型 | 文件 | 说明 |
|---|---|---|
| 本地存储 | internal/common/storage/local.go | 本地文件系统 |
| 阿里云 OSS | internal/common/storage/aliyun.go | 阿里云对象存储 |
接口说明
上传文件
请求:
POST /api/v1/files
Content-Type: multipart/form-data参数:
| 参数 | 类型 | 说明 |
|---|---|---|
| file | file | 上传的文件 |
| path | string | 存储路径前缀(可选,默认 uploads) |
响应:
json
{
"code": "00000",
"msg": "操作成功",
"data": {
"url": "http://example.com/files/2024/01/15/xxx.jpg",
"name": "xxx.jpg",
"path": "uploads/2024/01/15/xxx.jpg",
"size": 1024
}
}批量上传
POST /api/v1/files/batch
图片上传
POST /api/v1/files/image
删除文件
DELETE /api/v1/files?path=<文件存储路径>
存储配置
文件模块通过 storage.DefaultStorage 执行上传/删除,底层支持 local/aliyun 两种实现(见 internal/common/storage/*)。
注:当前仓库配置文件 configs/*.yaml 中未体现 storage 配置段,若你需要切换存储实现,需要在应用启动时初始化 storage.DefaultStorage(调用 storage.InitDefaultStorage(...))。
使用示例
客户端上传
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/file/router.go | 路由定义 |
internal/file/handler/file_handler.go | 文件处理 Handler |
internal/common/storage/local.go | 本地存储实现 |
internal/common/storage/aliyun.go | 阿里云 OSS 实现 |
