shudaooss.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. package controllers
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "image"
  7. "image/jpeg"
  8. "io"
  9. "math"
  10. "net/http"
  11. neturl "net/url"
  12. "path/filepath"
  13. "shudao-chat-go/utils"
  14. "strings"
  15. "time"
  16. "github.com/aws/aws-sdk-go/aws"
  17. "github.com/aws/aws-sdk-go/aws/credentials"
  18. "github.com/aws/aws-sdk-go/aws/session"
  19. "github.com/aws/aws-sdk-go/service/s3"
  20. "github.com/beego/beego/v2/server/web"
  21. )
  22. type ShudaoOssController struct {
  23. web.Controller
  24. }
  25. // OSS配置信息 - 根据测试文件更新配置
  26. var (
  27. ossBucket = "gdsc-ai-aqzs"
  28. ossAccessKey = "fnyfi2f368pbic74d8ll"
  29. ossSecretKey = "jgqwk7sirqlz2602x2k7yx2eor0vii19wah6ywlv" // 修正SecretKey
  30. ossEndpoint = "http://172.16.17.52:8060" // 添加http://前缀
  31. ossRegion = "us-east-1"
  32. )
  33. // 图片压缩配置
  34. const (
  35. // 目标文件大小(字节)
  36. TargetFileSize = 200 * 1024 // 200KB
  37. // 最大图片尺寸(像素)- 作为备选方案
  38. MaxImageWidth = 1920
  39. MaxImageHeight = 1080
  40. // JPEG压缩质量范围
  41. MinJPEGQuality = 10 // 最低质量
  42. MaxJPEGQuality = 95 // 最高质量
  43. // 是否启用图片压缩
  44. EnableImageCompression = true
  45. )
  46. // 上传响应结构
  47. type UploadResponse struct {
  48. StatusCode int `json:"statusCode"`
  49. Message string `json:"message"`
  50. FileURL string `json:"fileUrl"`
  51. FileName string `json:"fileName"`
  52. FileSize int64 `json:"fileSize"`
  53. }
  54. // 获取S3会话
  55. func getS3Session() (*session.Session, error) {
  56. // 检查时间同步
  57. now := time.Now()
  58. utcNow := now.UTC()
  59. fmt.Printf("=== S3会话创建调试信息 ===\n")
  60. fmt.Printf("本地时间: %s\n", now.Format("2006-01-02 15:04:05"))
  61. fmt.Printf("UTC时间: %s\n", utcNow.Format("2006-01-02 15:04:05"))
  62. fmt.Printf("时间差: %v\n", now.Sub(utcNow))
  63. fmt.Printf("Bucket: %s\n", ossBucket)
  64. fmt.Printf("Endpoint: %s\n", ossEndpoint)
  65. fmt.Printf("Region: %s\n", ossRegion)
  66. fmt.Printf("AccessKey: %s***\n", ossAccessKey[:8])
  67. s3Config := &aws.Config{
  68. Credentials: credentials.NewStaticCredentials(ossAccessKey, ossSecretKey, ""),
  69. Endpoint: aws.String(ossEndpoint),
  70. Region: aws.String(ossRegion),
  71. S3ForcePathStyle: aws.Bool(true), // 使用路径样式而不是虚拟主机样式
  72. DisableSSL: aws.Bool(true), // 如果endpoint是http则禁用SSL
  73. // 添加更多配置选项
  74. LogLevel: aws.LogLevel(aws.LogDebug), // 启用调试日志
  75. // 其他配置选项
  76. MaxRetries: aws.Int(3),
  77. // 其他配置选项
  78. }
  79. // 创建会话
  80. sess, err := session.NewSession(s3Config)
  81. if err != nil {
  82. return nil, err
  83. }
  84. // 验证凭据
  85. _, err = sess.Config.Credentials.Get()
  86. if err != nil {
  87. return nil, fmt.Errorf("凭据验证失败: %v", err)
  88. }
  89. return sess, nil
  90. }
  91. // 获取UTC时间同步的S3会话(根据测试文件优化配置)
  92. func getUTCS3Session() (*session.Session, error) {
  93. // 强制使用UTC时间
  94. utcNow := time.Now().UTC()
  95. fmt.Printf("=== UTC S3会话创建调试信息 ===\n")
  96. fmt.Printf("强制使用UTC时间: %s\n", utcNow.Format("2006-01-02 15:04:05"))
  97. fmt.Printf("Bucket: %s\n", ossBucket)
  98. fmt.Printf("Endpoint: %s\n", ossEndpoint)
  99. fmt.Printf("Region: %s\n", ossRegion)
  100. fmt.Printf("AccessKey: %s***\n", ossAccessKey[:8])
  101. // 创建S3配置 - 使用与测试文件相同的配置
  102. s3Config := &aws.Config{
  103. Credentials: credentials.NewStaticCredentials(ossAccessKey, ossSecretKey, ""),
  104. Endpoint: aws.String(ossEndpoint),
  105. Region: aws.String(ossRegion),
  106. S3ForcePathStyle: aws.Bool(true), // 强制使用路径样式(OSS兼容性需要)
  107. // 移除DisableSSL,因为endpoint已经包含http://
  108. // 移除LogLevel,减少调试输出
  109. // 移除MaxRetries,使用默认值
  110. // 移除S3DisableContentMD5Validation,使用默认值
  111. }
  112. // 创建会话
  113. sess, err := session.NewSession(s3Config)
  114. if err != nil {
  115. return nil, err
  116. }
  117. // 验证凭据
  118. _, err = sess.Config.Credentials.Get()
  119. if err != nil {
  120. return nil, fmt.Errorf("凭据验证失败: %v", err)
  121. }
  122. return sess, nil
  123. }
  124. // 判断是否为图片文件
  125. func isImageFile(ext string) bool {
  126. imageExts := map[string]bool{
  127. ".jpg": true,
  128. ".jpeg": true,
  129. ".png": true,
  130. ".gif": true,
  131. ".bmp": true,
  132. ".webp": true,
  133. ".tiff": true,
  134. ".svg": true,
  135. ".ico": true,
  136. }
  137. return imageExts[ext]
  138. }
  139. // 图片上传接口
  140. func (c *ShudaoOssController) UploadImage() {
  141. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
  142. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  143. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  144. if c.Ctx.Request.Method == "OPTIONS" {
  145. c.Ctx.ResponseWriter.WriteHeader(200)
  146. return
  147. }
  148. // 获取上传的图片文件
  149. file, header, err := c.GetFile("image")
  150. if err != nil {
  151. c.Data["json"] = UploadResponse{
  152. StatusCode: 400,
  153. Message: "获取上传图片失败: " + err.Error(),
  154. }
  155. c.ServeJSON()
  156. return
  157. }
  158. defer file.Close()
  159. // 检查文件扩展名
  160. ext := strings.ToLower(filepath.Ext(header.Filename))
  161. if !isImageFile(ext) {
  162. c.Data["json"] = UploadResponse{
  163. StatusCode: 400,
  164. Message: "不支持的文件格式,请上传图片文件(jpg, png, gif, bmp, webp等)",
  165. }
  166. c.ServeJSON()
  167. return
  168. }
  169. // 图片文件大小限制(10MB)
  170. if header.Size > 10*1024*1024 {
  171. c.Data["json"] = UploadResponse{
  172. StatusCode: 400,
  173. Message: "图片文件大小超过限制(10MB)",
  174. }
  175. c.ServeJSON()
  176. return
  177. }
  178. // 生成图片文件名(使用UTC时间)
  179. utcNow := time.Now().UTC()
  180. timestamp := utcNow.Unix()
  181. // 压缩后的图片统一使用.jpg扩展名
  182. fileName := fmt.Sprintf("images/%d/%s_%d.jpg",
  183. utcNow.Year(),
  184. utcNow.Format("0102"),
  185. timestamp)
  186. // 读取图片内容
  187. fileBytes, err := io.ReadAll(file)
  188. if err != nil {
  189. c.Data["json"] = UploadResponse{
  190. StatusCode: 500,
  191. Message: "读取图片内容失败: " + err.Error(),
  192. }
  193. c.ServeJSON()
  194. return
  195. }
  196. // 压缩图片
  197. if EnableImageCompression {
  198. fmt.Printf("开始压缩图片到200KB以下...\n")
  199. compressedBytes, err := compressImage(fileBytes, MaxImageWidth, MaxImageHeight, 0) // 参数不再使用
  200. if err != nil {
  201. fmt.Printf("图片压缩失败,使用原始图片: %v\n", err)
  202. // 压缩失败时使用原始图片
  203. } else {
  204. fmt.Printf("图片压缩完成,最终大小: %.2f KB\n", float64(len(compressedBytes))/1024)
  205. fileBytes = compressedBytes
  206. }
  207. } else {
  208. fmt.Printf("图片压缩已禁用,使用原始图片\n")
  209. }
  210. // 获取UTC时间同步的S3会话(解决时区问题)
  211. sess, err := getUTCS3Session()
  212. if err != nil {
  213. c.Data["json"] = UploadResponse{
  214. StatusCode: 500,
  215. Message: "创建S3会话失败: " + err.Error(),
  216. }
  217. c.ServeJSON()
  218. return
  219. }
  220. // 创建S3服务
  221. s3Client := s3.New(sess)
  222. // 打印上传信息
  223. fmt.Printf("正在上传图片: %s\n", fileName)
  224. fmt.Printf("文件大小: %.2f KB\n", float64(len(fileBytes))/1024)
  225. fmt.Printf("ContentType: %s\n", header.Header.Get("Content-Type"))
  226. // 上传图片到S3 - 使用与测试文件相同的上传方式
  227. _, err = s3Client.PutObject(&s3.PutObjectInput{
  228. Bucket: aws.String(ossBucket),
  229. Key: aws.String(fileName),
  230. Body: aws.ReadSeekCloser(strings.NewReader(string(fileBytes))), // 使用与测试文件相同的方式
  231. ACL: aws.String("public-read"),
  232. })
  233. if err != nil {
  234. fmt.Printf("上传图片失败: %v\n", err)
  235. c.Data["json"] = UploadResponse{
  236. StatusCode: 500,
  237. Message: "上传图片到OSS失败: " + err.Error(),
  238. }
  239. c.ServeJSON()
  240. return
  241. }
  242. // // 生成预签名URL(1小时有效期)
  243. // req, _ := s3Client.GetObjectRequest(&s3.GetObjectInput{
  244. // Bucket: aws.String(ossBucket),
  245. // Key: aws.String(fileName),
  246. // })
  247. // presignedURL, err := req.Presign(24 * time.Hour)
  248. // if err != nil {
  249. // fmt.Printf("生成预签名URL失败: %v\n", err)
  250. // // 如果预签名URL生成失败,使用简单URL作为备选
  251. // imageURL := fmt.Sprintf("%s/%s", ossEndpoint, fileName)
  252. // c.Data["json"] = UploadResponse{
  253. // StatusCode: 200,
  254. // Message: "图片上传成功,但预签名URL生成失败",
  255. // FileURL: imageURL,
  256. // FileName: fileName,
  257. // FileSize: header.Size,
  258. // }
  259. // c.ServeJSON()
  260. // return
  261. // }
  262. permanentURL := fmt.Sprintf("%s/%s/%s", ossEndpoint, ossBucket, fileName)
  263. // 使用代理接口包装URL,前端需要预览图片
  264. proxyURL := utils.GetProxyURL(permanentURL)
  265. fmt.Printf("图片上传成功: %s\n", fileName)
  266. fmt.Printf("文件URL: %s\n", permanentURL)
  267. fmt.Printf("代理URL: %s\n", proxyURL)
  268. c.Data["json"] = UploadResponse{
  269. StatusCode: 200,
  270. Message: "图片上传成功",
  271. FileURL: proxyURL,
  272. FileName: fileName,
  273. FileSize: int64(len(fileBytes)), // 使用压缩后的文件大小
  274. }
  275. c.ServeJSON()
  276. }
  277. // 上传PPTjson文件
  278. func (c *ShudaoOssController) UploadPPTJson() {
  279. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
  280. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  281. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  282. if c.Ctx.Request.Method == "OPTIONS" {
  283. c.Ctx.ResponseWriter.WriteHeader(200)
  284. return
  285. }
  286. // 获取上传的JSON文件
  287. file, header, err := c.GetFile("json")
  288. if err != nil {
  289. c.Data["json"] = UploadResponse{
  290. StatusCode: 400,
  291. Message: "获取上传JSON文件失败: " + err.Error(),
  292. }
  293. c.ServeJSON()
  294. return
  295. }
  296. defer file.Close()
  297. // 检查文件扩展名
  298. ext := strings.ToLower(filepath.Ext(header.Filename))
  299. if ext != ".json" {
  300. c.Data["json"] = UploadResponse{
  301. StatusCode: 400,
  302. Message: "不支持的文件格式,请上传JSON文件(.json)",
  303. }
  304. c.ServeJSON()
  305. return
  306. }
  307. // JSON文件大小限制(50MB)
  308. if header.Size > 50*1024*1024 {
  309. c.Data["json"] = UploadResponse{
  310. StatusCode: 400,
  311. Message: "JSON文件大小超过限制(50MB)",
  312. }
  313. c.ServeJSON()
  314. return
  315. }
  316. // 生成JSON文件名(使用UTC时间)
  317. utcNow := time.Now().UTC()
  318. timestamp := utcNow.Unix()
  319. fileName := fmt.Sprintf("json/%d/%s_%d%s",
  320. utcNow.Year(),
  321. utcNow.Format("0102"),
  322. timestamp,
  323. ext)
  324. // 读取JSON内容
  325. fileBytes, err := io.ReadAll(file)
  326. if err != nil {
  327. c.Data["json"] = UploadResponse{
  328. StatusCode: 500,
  329. Message: "读取JSON内容失败: " + err.Error(),
  330. }
  331. c.ServeJSON()
  332. return
  333. }
  334. // 验证JSON格式
  335. var jsonData interface{}
  336. if err := json.Unmarshal(fileBytes, &jsonData); err != nil {
  337. c.Data["json"] = UploadResponse{
  338. StatusCode: 400,
  339. Message: "JSON格式无效: " + err.Error(),
  340. }
  341. c.ServeJSON()
  342. return
  343. }
  344. // 获取UTC时间同步的S3会话
  345. sess, err := getUTCS3Session()
  346. if err != nil {
  347. c.Data["json"] = UploadResponse{
  348. StatusCode: 500,
  349. Message: "创建S3会话失败: " + err.Error(),
  350. }
  351. c.ServeJSON()
  352. return
  353. }
  354. // 创建S3服务
  355. s3Client := s3.New(sess)
  356. // 打印上传信息
  357. fmt.Printf("正在上传JSON文件: %s\n", fileName)
  358. fmt.Printf("文件大小: %.2f KB\n", float64(len(fileBytes))/1024)
  359. fmt.Printf("ContentType: %s\n", header.Header.Get("Content-Type"))
  360. // 上传JSON到S3
  361. _, err = s3Client.PutObject(&s3.PutObjectInput{
  362. Bucket: aws.String(ossBucket),
  363. Key: aws.String(fileName),
  364. Body: aws.ReadSeekCloser(strings.NewReader(string(fileBytes))),
  365. ACL: aws.String("public-read"),
  366. ContentType: aws.String("application/json"),
  367. })
  368. if err != nil {
  369. fmt.Printf("上传JSON文件失败: %v\n", err)
  370. c.Data["json"] = UploadResponse{
  371. StatusCode: 500,
  372. Message: "上传JSON文件到OSS失败: " + err.Error(),
  373. }
  374. c.ServeJSON()
  375. return
  376. }
  377. // 生成永久URL
  378. permanentURL := fmt.Sprintf("%s/%s/%s", ossEndpoint, ossBucket, fileName)
  379. // 使用代理接口包装URL,前端需要访问文件
  380. proxyURL := utils.GetProxyURL(permanentURL)
  381. fmt.Printf("JSON文件上传成功: %s\n", fileName)
  382. fmt.Printf("文件URL: %s\n", permanentURL)
  383. fmt.Printf("代理URL: %s\n", proxyURL)
  384. c.Data["json"] = UploadResponse{
  385. StatusCode: 200,
  386. Message: "JSON文件上传成功",
  387. FileURL: proxyURL,
  388. FileName: fileName,
  389. FileSize: header.Size,
  390. }
  391. c.ServeJSON()
  392. }
  393. // ParseOSS OSS代理解析接口,用于代理转发OSS URL请求
  394. func (c *ShudaoOssController) ParseOSS() {
  395. // 设置CORS头
  396. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
  397. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  398. c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  399. // 处理OPTIONS预检请求
  400. if c.Ctx.Request.Method == "OPTIONS" {
  401. c.Ctx.ResponseWriter.WriteHeader(200)
  402. return
  403. }
  404. // 获取URL参数
  405. ossURL := c.GetString("url")
  406. if ossURL == "" {
  407. c.Ctx.ResponseWriter.WriteHeader(400)
  408. c.Ctx.WriteString("缺少url参数")
  409. return
  410. }
  411. // URL解码,处理可能的编码问题
  412. decodedURL, err := neturl.QueryUnescape(ossURL)
  413. if err != nil {
  414. fmt.Printf("URL解码失败: %v, 原始URL: %s\n", err, ossURL)
  415. // 如果解码失败,使用原始URL
  416. decodedURL = ossURL
  417. }
  418. var actualOSSURL string
  419. // 检查是否是代理URL格式(包含?url=参数)
  420. if strings.Contains(decodedURL, "?url=") {
  421. // 解析代理URL,提取实际的OSS URL
  422. parsedProxyURL, err := neturl.Parse(decodedURL)
  423. if err != nil {
  424. fmt.Printf("代理URL解析失败: %v, 解码后URL: %s\n", err, decodedURL)
  425. c.Ctx.ResponseWriter.WriteHeader(400)
  426. c.Ctx.WriteString("代理URL格式无效: " + err.Error())
  427. return
  428. }
  429. // 获取实际的OSS URL
  430. actualOSSURL = parsedProxyURL.Query().Get("url")
  431. if actualOSSURL == "" {
  432. fmt.Printf("代理URL中缺少url参数: %s\n", decodedURL)
  433. c.Ctx.ResponseWriter.WriteHeader(400)
  434. c.Ctx.WriteString("代理URL中缺少url参数")
  435. return
  436. }
  437. } else {
  438. // 直接使用传入的URL作为OSS URL
  439. actualOSSURL = decodedURL
  440. fmt.Printf("检测到直接OSS URL: %s\n", actualOSSURL)
  441. }
  442. // 验证实际OSS URL格式
  443. parsedOSSURL, err := neturl.Parse(actualOSSURL)
  444. if err != nil {
  445. fmt.Printf("OSS URL解析失败: %v, OSS URL: %s\n", err, actualOSSURL)
  446. c.Ctx.ResponseWriter.WriteHeader(400)
  447. c.Ctx.WriteString("OSS URL格式无效: " + err.Error())
  448. return
  449. }
  450. if parsedOSSURL.Scheme == "" {
  451. fmt.Printf("OSS URL缺少协议方案: %s\n", actualOSSURL)
  452. c.Ctx.ResponseWriter.WriteHeader(400)
  453. c.Ctx.WriteString("OSS URL缺少协议方案")
  454. return
  455. }
  456. fmt.Printf("代理请求 - 原始URL: %s, 解码后URL: %s, 实际OSS URL: %s, 协议: %s\n",
  457. ossURL, decodedURL, actualOSSURL, parsedOSSURL.Scheme)
  458. // 创建HTTP客户端,设置超时时间
  459. client := &http.Client{
  460. Timeout: 30 * time.Second,
  461. }
  462. // 发送GET请求到实际的OSS URL
  463. resp, err := client.Get(actualOSSURL)
  464. if err != nil {
  465. c.Ctx.ResponseWriter.WriteHeader(502)
  466. c.Ctx.WriteString("无法连接到OSS: " + err.Error())
  467. return
  468. }
  469. defer resp.Body.Close()
  470. // 检查HTTP状态码
  471. if resp.StatusCode != http.StatusOK {
  472. c.Ctx.ResponseWriter.WriteHeader(resp.StatusCode)
  473. c.Ctx.WriteString(fmt.Sprintf("OSS返回错误: %d", resp.StatusCode))
  474. return
  475. }
  476. // 读取响应内容
  477. content, err := io.ReadAll(resp.Body)
  478. if err != nil {
  479. c.Ctx.ResponseWriter.WriteHeader(500)
  480. c.Ctx.WriteString("读取OSS响应失败: " + err.Error())
  481. return
  482. }
  483. // 获取原始的content-type
  484. contentType := resp.Header.Get("content-type")
  485. if contentType == "" {
  486. contentType = "application/octet-stream"
  487. }
  488. // 如果OSS返回的是binary/octet-stream或application/octet-stream,
  489. // 尝试根据URL文件扩展名推断正确的MIME类型
  490. if contentType == "binary/octet-stream" || contentType == "application/octet-stream" {
  491. // 解析URL获取文件路径
  492. parsedURL, err := neturl.Parse(actualOSSURL)
  493. if err == nil {
  494. filePath := parsedURL.Path
  495. // URL解码,处理中文文件名
  496. filePath, err = neturl.QueryUnescape(filePath)
  497. if err == nil {
  498. // 根据文件扩展名猜测MIME类型
  499. if strings.HasSuffix(strings.ToLower(filePath), ".jpg") || strings.HasSuffix(strings.ToLower(filePath), ".jpeg") {
  500. contentType = "image/jpeg"
  501. } else if strings.HasSuffix(strings.ToLower(filePath), ".png") {
  502. contentType = "image/png"
  503. } else if strings.HasSuffix(strings.ToLower(filePath), ".gif") {
  504. contentType = "image/gif"
  505. } else if strings.HasSuffix(strings.ToLower(filePath), ".pdf") {
  506. contentType = "application/pdf"
  507. } else if strings.HasSuffix(strings.ToLower(filePath), ".json") {
  508. contentType = "application/json"
  509. } else if strings.HasSuffix(strings.ToLower(filePath), ".txt") {
  510. contentType = "text/plain"
  511. }
  512. }
  513. }
  514. }
  515. // 设置响应头
  516. c.Ctx.ResponseWriter.Header().Set("Content-Type", contentType)
  517. c.Ctx.ResponseWriter.Header().Set("Content-Length", fmt.Sprintf("%d", len(content)))
  518. // 转发重要的响应头
  519. importantHeaders := []string{
  520. "content-disposition",
  521. "cache-control",
  522. "etag",
  523. "last-modified",
  524. "accept-ranges",
  525. }
  526. for _, header := range importantHeaders {
  527. if value := resp.Header.Get(header); value != "" {
  528. c.Ctx.ResponseWriter.Header().Set(header, value)
  529. }
  530. }
  531. // 写入响应内容
  532. c.Ctx.ResponseWriter.WriteHeader(200)
  533. c.Ctx.ResponseWriter.Write(content)
  534. }
  535. // compressImage 压缩图片到目标大小
  536. func compressImage(imageData []byte, maxWidth, maxHeight int, quality int) ([]byte, error) {
  537. // 解码图片
  538. img, format, err := image.Decode(bytes.NewReader(imageData))
  539. if err != nil {
  540. return nil, fmt.Errorf("解码图片失败: %v", err)
  541. }
  542. // 获取原始尺寸
  543. bounds := img.Bounds()
  544. originalWidth := bounds.Dx()
  545. originalHeight := bounds.Dy()
  546. originalSize := len(imageData)
  547. fmt.Printf("原始图片: %dx%d, 格式: %s, 大小: %.2f KB\n",
  548. originalWidth, originalHeight, format, float64(originalSize)/1024)
  549. // 如果原始文件已经小于目标大小,直接返回
  550. if originalSize <= TargetFileSize {
  551. fmt.Printf("文件已小于目标大小,无需压缩\n")
  552. return imageData, nil
  553. }
  554. // 尝试不同的压缩策略
  555. compressedData, err := compressToTargetSize(img, originalSize)
  556. if err != nil {
  557. return nil, err
  558. }
  559. finalSize := len(compressedData)
  560. compressionRatio := float64(finalSize) / float64(originalSize) * 100
  561. fmt.Printf("压缩完成: %.2f KB -> %.2f KB (压缩率: %.1f%%)\n",
  562. float64(originalSize)/1024,
  563. float64(finalSize)/1024,
  564. compressionRatio)
  565. return compressedData, nil
  566. }
  567. // compressToTargetSize 压缩到目标文件大小
  568. func compressToTargetSize(img image.Image, originalSize int) ([]byte, error) {
  569. bounds := img.Bounds()
  570. originalWidth := bounds.Dx()
  571. originalHeight := bounds.Dy()
  572. // 策略1: 先尝试调整质量,不改变尺寸
  573. fmt.Printf("策略1: 调整质量压缩...\n")
  574. compressedData, err := compressByQuality(img, originalSize)
  575. if err == nil && len(compressedData) <= TargetFileSize {
  576. fmt.Printf("质量压缩成功,达到目标大小\n")
  577. return compressedData, nil
  578. }
  579. // 策略2: 如果质量压缩不够,尝试缩小尺寸
  580. fmt.Printf("策略2: 尺寸+质量压缩...\n")
  581. // 计算需要缩小的比例
  582. targetRatio := float64(TargetFileSize) / float64(originalSize)
  583. sizeRatio := math.Sqrt(targetRatio * 0.8) // 留一些余量给质量调整
  584. newWidth := int(float64(originalWidth) * sizeRatio)
  585. newHeight := int(float64(originalHeight) * sizeRatio)
  586. // 确保最小尺寸
  587. if newWidth < 100 {
  588. newWidth = 100
  589. }
  590. if newHeight < 100 {
  591. newHeight = 100
  592. }
  593. fmt.Printf("调整尺寸: %dx%d -> %dx%d\n", originalWidth, originalHeight, newWidth, newHeight)
  594. // 调整图片尺寸
  595. resizedImg := resizeImage(img, newWidth, newHeight)
  596. // 再次尝试质量压缩
  597. return compressByQuality(resizedImg, originalSize)
  598. }
  599. // compressByQuality 通过调整质量压缩图片
  600. func compressByQuality(img image.Image, originalSize int) ([]byte, error) {
  601. var bestResult []byte
  602. var bestSize int = originalSize
  603. // 从高质量到低质量尝试
  604. qualities := []int{85, 70, 60, 50, 40, 30, 25, 20, 15, 10}
  605. for _, quality := range qualities {
  606. var buf bytes.Buffer
  607. if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil {
  608. continue
  609. }
  610. currentSize := buf.Len()
  611. fmt.Printf(" 质量 %d: %.2f KB\n", quality, float64(currentSize)/1024)
  612. // 如果达到目标大小,直接返回
  613. if currentSize <= TargetFileSize {
  614. fmt.Printf(" 达到目标大小,质量: %d\n", quality)
  615. return buf.Bytes(), nil
  616. }
  617. // 记录最佳结果
  618. if currentSize < bestSize {
  619. bestSize = currentSize
  620. bestResult = buf.Bytes()
  621. }
  622. }
  623. // 如果没有达到目标大小,返回最佳结果
  624. if bestResult != nil {
  625. fmt.Printf(" 未达到目标大小,使用最佳结果: %.2f KB\n", float64(bestSize)/1024)
  626. return bestResult, nil
  627. }
  628. return nil, fmt.Errorf("压缩失败")
  629. }
  630. // resizeImage 调整图片尺寸
  631. func resizeImage(img image.Image, newWidth, newHeight int) image.Image {
  632. // 创建新的图片
  633. resized := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight))
  634. // 简单的最近邻插值缩放
  635. bounds := img.Bounds()
  636. for y := 0; y < newHeight; y++ {
  637. for x := 0; x < newWidth; x++ {
  638. // 计算原始图片中的对应位置
  639. srcX := int(float64(x) * float64(bounds.Dx()) / float64(newWidth))
  640. srcY := int(float64(y) * float64(bounds.Dy()) / float64(newHeight))
  641. // 确保不超出边界
  642. if srcX >= bounds.Dx() {
  643. srcX = bounds.Dx() - 1
  644. }
  645. if srcY >= bounds.Dy() {
  646. srcY = bounds.Dy() - 1
  647. }
  648. resized.Set(x, y, img.At(bounds.Min.X+srcX, bounds.Min.Y+srcY))
  649. }
  650. }
  651. return resized
  652. }