Files
my-springboot-project/docs/图片URL优化更新文档.md
2026-06-03 12:43:48 +08:00

71 lines
2.1 KiB
Markdown
Raw 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.
# 图片 URL 优化更新文档
## 概述
本次更新优化了图片访问方式,从原来通过后端 API 代理访问改为直接通过 Nginx 静态资源访问,提高了图片加载效率。
## 修改内容
### 1. 配置文件
- 使用配置项 `file.upload.path` 确定本地保存路径
- 使用配置项 `file.upload.url-prefix` 确定 Nginx 访问前缀(默认为 `/files/`
### 2. ImageService 接口
- 新增 `getNginxUrlByImageId(String imageId)` 方法,用于根据图片 ID 获取 Nginx 格式的 URL
### 3. ImageServiceImpl 实现
- 使用配置的 `file.upload.path` + `/img` 作为图片存储目录
- 保存图片时返回相对路径(如 `img/xxx.jpg`)而非绝对路径
- 修改本地读取图片逻辑,支持相对路径
- 新增 `getNginxUrlByImageId` 方法
- 新增 `extractFilenameFromPath` 辅助方法
### 4. AiChatServiceImpl 修改
- 在保存图片后立即更新 imageMetadata 中的 url 为 Nginx 格式
- 在 SSE 的 finish 事件中,对无 metadata 的图片也尝试生成 Nginx 格式 URL
### 5. ChatServiceImpl 修改
- 查看历史记录时,将图片 URL 从 `/api/image/xxx/data` 转换为 Nginx 格式(`/files/img/xxx.jpg`
## 使用示例
### Nginx 配置示例
```nginx
server {
listen 80;
location /files/ {
alias /path/to/upload/;
expires 7d;
add_header Cache-Control "public, immutable";
}
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
### 配置文件 (application-prod.yml)
```yaml
file:
upload:
path: /opt/deploy/uploads/
url-prefix: /files/
```
## 部署说明
1. 确保 Nginx 配置正确,`/files/` 路径指向实际的上传目录
2. 确保应用配置文件中的 `file.upload.path``file.upload.url-prefix` 设置正确
3. 重新构建并部署应用
## 兼容性
- 保留了向后兼容,如果 Nginx 格式 URL 无法获取,会回退为原 `/api/image/xxx/data` 格式
- 旧数据仍然可以正常访问
## 图片 URL 格式对比
| 旧格式 | 新格式 |
|--------|--------|
| /api/image/xxx/data | /files/img/xxx.jpg |