yunzer_go/server/docs/UPLOAD_PATH.md
2025-10-28 17:22:27 +08:00

165 lines
3.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 文件上传路径说明
## 当前配置
### 文件保存路径
文件保存在项目根目录的 `front/uploads/` 目录下,按照日期自动分类:
```
项目根目录/
├── server/
│ └── controllers/
│ └── file.go (处理上传)
├── front/
│ └── uploads/ ← 文件保存位置
│ ├── 2024/
│ │ └── 01/
│ │ └── 15/
│ │ └── 20240115143045_example.jpg
```
### 代码中的路径
`server/controllers/file.go``Post()` 方法中:
```go
// 构造保存路径:../front/uploads/年/月/日/
uploadDir := path.Join("..", "front", "uploads", datePath)
```
**说明**
- `..` 表示从 server 目录向上一级到项目根目录
- `front/uploads/` 是上传文件的根目录
- `datePath` 是按日期自动生成的子目录(如 `2024/01/15`
### 静态文件访问配置
`server/conf/app.conf` 中:
```conf
StaticDir = /uploads:../front/uploads
```
**说明**
- `/uploads` 是 URL 访问路径
- `../front/uploads` 是实际文件存储路径(相对于 server 目录)
## 目录结构
### 保存到数据库的路径
- `file_path`: `uploads/2024/01/15/20240115143045_example.jpg`(相对路径)
- `file_url`: `/uploads/2024/01/15/20240115143045_example.jpg`URL 路径)
### 实际文件系统路径
```
front/uploads/2024/01/15/20240115143045_example.jpg
```
### 访问 URL
```
http://localhost:8080/uploads/2024/01/15/20240115143045_example.jpg
```
## 为什么使用相对路径 `..`
由于项目结构是:
```
yunzer_go/
├── server/ ← 服务端代码
└── front/ ← 前端代码和上传文件
└── uploads/
```
`server` 目录运行应用时,要访问 `front/uploads`,需要使用 `../front/uploads`
## 如果路径不对怎么办?
### 方案1修改代码中的路径
如果您的项目启动目录不同,可以修改 `file.go` 中的路径:
```go
// 如果从项目根目录运行
uploadDir := path.Join("front", "uploads", datePath)
// 或者使用绝对路径
uploadDir := path.Join("/path/to/project", "front", "uploads", datePath)
```
### 方案2从配置文件读取
`app.conf` 中添加配置:
```conf
# 上传文件目录
uploadDir = ../front/uploads
```
然后在代码中读取:
```go
import "github.com/beego/beego/v2/server/web"
uploadDir := path.Join(
web.AppConfig.String("uploadDir"),
datePath,
)
```
## 验证路径是否正确
### 1. 检查文件保存位置
上传一个文件后,查看文件是否在正确的位置:
```bash
ls front/uploads/
```
应该看到按日期分类的文件夹和文件。
### 2. 检查数据库记录
查看 `yz_files` 表中的 `file_path` 字段:
```sql
SELECT file_path, file_url FROM yz_files ORDER BY upload_time DESC LIMIT 1;
```
应该看到类似:
```
file_path: uploads/2024/01/15/20240115143045_example.jpg
file_url: /uploads/2024/01/15/20240115143045_example.jpg
```
### 3. 检查 URL 访问
直接在浏览器访问:
```
http://localhost:8080/uploads/2024/01/15/文件名
```
如果能看到文件,说明路径配置正确。
## 常见问题
### Q: 文件保存在了 server/front/uploads
A: 修改代码中的路径为 `../front/uploads`(已经修改)
### Q: 文件保存在了 front/front/uploads
A: 检查当前工作目录,确保在 server 目录运行应用
### Q: 访问文件返回 404
A: 检查 `app.conf` 中的 StaticDir 配置是否正确
### Q: 权限问题?
A: 确保应用有创建目录和写入文件的权限:
```bash
chmod 755 front/uploads
```
## 建议的改进
如果需要更可靠的路径处理,可以考虑:
1. **使用绝对路径**:从配置文件或环境变量读取项目根目录
2. **路径验证**:在应用启动时检查上传目录是否存在,不存在则创建
3. **日志记录**:记录文件保存的完整路径,便于调试