shudaooss.go 21 KB

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