shudaooss.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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. encryptedURL := c.GetString("url")
  406. if encryptedURL == "" {
  407. c.Ctx.ResponseWriter.WriteHeader(400)
  408. c.Ctx.WriteString("缺少url参数")
  409. return
  410. }
  411. // 解密URL
  412. decryptedURL, err := utils.DecryptURL(encryptedURL)
  413. if err != nil {
  414. fmt.Printf("URL解密失败: %v, 加密URL: %s\n", err, encryptedURL)
  415. c.Ctx.ResponseWriter.WriteHeader(400)
  416. c.Ctx.WriteString("URL解密失败: " + err.Error())
  417. return
  418. }
  419. // URL解码,处理可能的编码问题
  420. decodedURL, err := neturl.QueryUnescape(decryptedURL)
  421. if err != nil {
  422. fmt.Printf("URL解码失败: %v, 解密后URL: %s\n", err, decryptedURL)
  423. // 如果解码失败,使用解密后的URL
  424. decodedURL = decryptedURL
  425. }
  426. var actualOSSURL string
  427. // 检查是否是代理URL格式(包含?url=参数)
  428. if strings.Contains(decodedURL, "?url=") {
  429. // 解析代理URL,提取实际的OSS URL
  430. parsedProxyURL, err := neturl.Parse(decodedURL)
  431. if err != nil {
  432. fmt.Printf("代理URL解析失败: %v, 解码后URL: %s\n", err, decodedURL)
  433. c.Ctx.ResponseWriter.WriteHeader(400)
  434. c.Ctx.WriteString("代理URL格式无效: " + err.Error())
  435. return
  436. }
  437. // 获取实际的OSS URL
  438. actualOSSURL = parsedProxyURL.Query().Get("url")
  439. if actualOSSURL == "" {
  440. fmt.Printf("代理URL中缺少url参数: %s\n", decodedURL)
  441. c.Ctx.ResponseWriter.WriteHeader(400)
  442. c.Ctx.WriteString("代理URL中缺少url参数")
  443. return
  444. }
  445. } else {
  446. // 直接使用传入的URL作为OSS URL
  447. actualOSSURL = decodedURL
  448. fmt.Printf("检测到直接OSS URL: %s\n", actualOSSURL)
  449. }
  450. // 验证实际OSS URL格式
  451. parsedOSSURL, err := neturl.Parse(actualOSSURL)
  452. if err != nil {
  453. fmt.Printf("OSS URL解析失败: %v, OSS URL: %s\n", err, actualOSSURL)
  454. c.Ctx.ResponseWriter.WriteHeader(400)
  455. c.Ctx.WriteString("OSS URL格式无效: " + err.Error())
  456. return
  457. }
  458. if parsedOSSURL.Scheme == "" {
  459. fmt.Printf("OSS URL缺少协议方案: %s\n", actualOSSURL)
  460. c.Ctx.ResponseWriter.WriteHeader(400)
  461. c.Ctx.WriteString("OSS URL缺少协议方案")
  462. return
  463. }
  464. fmt.Printf("代理请求 - 加密URL: %s, 解密后URL: %s, 解码后URL: %s, 实际OSS URL: %s, 协议: %s\n",
  465. encryptedURL, decryptedURL, decodedURL, actualOSSURL, parsedOSSURL.Scheme)
  466. // 创建HTTP客户端,设置超时时间
  467. client := &http.Client{
  468. Timeout: 30 * time.Second,
  469. }
  470. // 发送GET请求到实际的OSS URL
  471. resp, err := client.Get(actualOSSURL)
  472. if err != nil {
  473. c.Ctx.ResponseWriter.WriteHeader(502)
  474. c.Ctx.WriteString("无法连接到OSS: " + err.Error())
  475. return
  476. }
  477. defer resp.Body.Close()
  478. // 检查HTTP状态码
  479. if resp.StatusCode != http.StatusOK {
  480. c.Ctx.ResponseWriter.WriteHeader(resp.StatusCode)
  481. c.Ctx.WriteString(fmt.Sprintf("OSS返回错误: %d", resp.StatusCode))
  482. return
  483. }
  484. // 读取响应内容
  485. content, err := io.ReadAll(resp.Body)
  486. if err != nil {
  487. c.Ctx.ResponseWriter.WriteHeader(500)
  488. c.Ctx.WriteString("读取OSS响应失败: " + err.Error())
  489. return
  490. }
  491. // 获取原始的content-type
  492. contentType := resp.Header.Get("content-type")
  493. if contentType == "" {
  494. contentType = "application/octet-stream"
  495. }
  496. // 如果OSS返回的是binary/octet-stream或application/octet-stream,
  497. // 尝试根据URL文件扩展名推断正确的MIME类型
  498. if contentType == "binary/octet-stream" || contentType == "application/octet-stream" {
  499. // 解析URL获取文件路径
  500. parsedURL, err := neturl.Parse(actualOSSURL)
  501. if err == nil {
  502. filePath := parsedURL.Path
  503. // URL解码,处理中文文件名
  504. filePath, err = neturl.QueryUnescape(filePath)
  505. if err == nil {
  506. // 根据文件扩展名猜测MIME类型
  507. if strings.HasSuffix(strings.ToLower(filePath), ".jpg") || strings.HasSuffix(strings.ToLower(filePath), ".jpeg") {
  508. contentType = "image/jpeg"
  509. } else if strings.HasSuffix(strings.ToLower(filePath), ".png") {
  510. contentType = "image/png"
  511. } else if strings.HasSuffix(strings.ToLower(filePath), ".gif") {
  512. contentType = "image/gif"
  513. } else if strings.HasSuffix(strings.ToLower(filePath), ".pdf") {
  514. contentType = "application/pdf"
  515. } else if strings.HasSuffix(strings.ToLower(filePath), ".json") {
  516. contentType = "application/json"
  517. } else if strings.HasSuffix(strings.ToLower(filePath), ".txt") {
  518. contentType = "text/plain"
  519. }
  520. }
  521. }
  522. }
  523. // 设置响应头
  524. c.Ctx.ResponseWriter.Header().Set("Content-Type", contentType)
  525. c.Ctx.ResponseWriter.Header().Set("Content-Length", fmt.Sprintf("%d", len(content)))
  526. // 转发重要的响应头
  527. importantHeaders := []string{
  528. "content-disposition",
  529. "cache-control",
  530. "etag",
  531. "last-modified",
  532. "accept-ranges",
  533. }
  534. for _, header := range importantHeaders {
  535. if value := resp.Header.Get(header); value != "" {
  536. c.Ctx.ResponseWriter.Header().Set(header, value)
  537. }
  538. }
  539. // 写入响应内容
  540. c.Ctx.ResponseWriter.WriteHeader(200)
  541. c.Ctx.ResponseWriter.Write(content)
  542. }
  543. // compressImage 压缩图片到目标大小
  544. func compressImage(imageData []byte, maxWidth, maxHeight int, quality int) ([]byte, error) {
  545. // 解码图片
  546. img, format, err := image.Decode(bytes.NewReader(imageData))
  547. if err != nil {
  548. return nil, fmt.Errorf("解码图片失败: %v", err)
  549. }
  550. // 获取原始尺寸
  551. bounds := img.Bounds()
  552. originalWidth := bounds.Dx()
  553. originalHeight := bounds.Dy()
  554. originalSize := len(imageData)
  555. fmt.Printf("原始图片: %dx%d, 格式: %s, 大小: %.2f KB\n",
  556. originalWidth, originalHeight, format, float64(originalSize)/1024)
  557. // 如果原始文件已经小于目标大小,直接返回
  558. if originalSize <= TargetFileSize {
  559. fmt.Printf("文件已小于目标大小,无需压缩\n")
  560. return imageData, nil
  561. }
  562. // 尝试不同的压缩策略
  563. compressedData, err := compressToTargetSize(img, originalSize)
  564. if err != nil {
  565. return nil, err
  566. }
  567. finalSize := len(compressedData)
  568. compressionRatio := float64(finalSize) / float64(originalSize) * 100
  569. fmt.Printf("压缩完成: %.2f KB -> %.2f KB (压缩率: %.1f%%)\n",
  570. float64(originalSize)/1024,
  571. float64(finalSize)/1024,
  572. compressionRatio)
  573. return compressedData, nil
  574. }
  575. // compressToTargetSize 压缩到目标文件大小
  576. func compressToTargetSize(img image.Image, originalSize int) ([]byte, error) {
  577. bounds := img.Bounds()
  578. originalWidth := bounds.Dx()
  579. originalHeight := bounds.Dy()
  580. // 策略1: 先尝试调整质量,不改变尺寸
  581. fmt.Printf("策略1: 调整质量压缩...\n")
  582. compressedData, err := compressByQuality(img, originalSize)
  583. if err == nil && len(compressedData) <= TargetFileSize {
  584. fmt.Printf("质量压缩成功,达到目标大小\n")
  585. return compressedData, nil
  586. }
  587. // 策略2: 如果质量压缩不够,尝试缩小尺寸
  588. fmt.Printf("策略2: 尺寸+质量压缩...\n")
  589. // 计算需要缩小的比例
  590. targetRatio := float64(TargetFileSize) / float64(originalSize)
  591. sizeRatio := math.Sqrt(targetRatio * 0.8) // 留一些余量给质量调整
  592. newWidth := int(float64(originalWidth) * sizeRatio)
  593. newHeight := int(float64(originalHeight) * sizeRatio)
  594. // 确保最小尺寸
  595. if newWidth < 100 {
  596. newWidth = 100
  597. }
  598. if newHeight < 100 {
  599. newHeight = 100
  600. }
  601. fmt.Printf("调整尺寸: %dx%d -> %dx%d\n", originalWidth, originalHeight, newWidth, newHeight)
  602. // 调整图片尺寸
  603. resizedImg := resizeImage(img, newWidth, newHeight)
  604. // 再次尝试质量压缩
  605. return compressByQuality(resizedImg, originalSize)
  606. }
  607. // compressByQuality 通过调整质量压缩图片
  608. func compressByQuality(img image.Image, originalSize int) ([]byte, error) {
  609. var bestResult []byte
  610. var bestSize int = originalSize
  611. // 从高质量到低质量尝试
  612. qualities := []int{85, 70, 60, 50, 40, 30, 25, 20, 15, 10}
  613. for _, quality := range qualities {
  614. var buf bytes.Buffer
  615. if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil {
  616. continue
  617. }
  618. currentSize := buf.Len()
  619. fmt.Printf(" 质量 %d: %.2f KB\n", quality, float64(currentSize)/1024)
  620. // 如果达到目标大小,直接返回
  621. if currentSize <= TargetFileSize {
  622. fmt.Printf(" 达到目标大小,质量: %d\n", quality)
  623. return buf.Bytes(), nil
  624. }
  625. // 记录最佳结果
  626. if currentSize < bestSize {
  627. bestSize = currentSize
  628. bestResult = buf.Bytes()
  629. }
  630. }
  631. // 如果没有达到目标大小,返回最佳结果
  632. if bestResult != nil {
  633. fmt.Printf(" 未达到目标大小,使用最佳结果: %.2f KB\n", float64(bestSize)/1024)
  634. return bestResult, nil
  635. }
  636. return nil, fmt.Errorf("压缩失败")
  637. }
  638. // resizeImage 调整图片尺寸
  639. func resizeImage(img image.Image, newWidth, newHeight int) image.Image {
  640. // 创建新的图片
  641. resized := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight))
  642. // 简单的最近邻插值缩放
  643. bounds := img.Bounds()
  644. for y := 0; y < newHeight; y++ {
  645. for x := 0; x < newWidth; x++ {
  646. // 计算原始图片中的对应位置
  647. srcX := int(float64(x) * float64(bounds.Dx()) / float64(newWidth))
  648. srcY := int(float64(y) * float64(bounds.Dy()) / float64(newHeight))
  649. // 确保不超出边界
  650. if srcX >= bounds.Dx() {
  651. srcX = bounds.Dx() - 1
  652. }
  653. if srcY >= bounds.Dy() {
  654. srcY = bounds.Dy() - 1
  655. }
  656. resized.Set(x, y, img.At(bounds.Min.X+srcX, bounds.Min.Y+srcY))
  657. }
  658. }
  659. return resized
  660. }