package controllers import ( "bytes" "encoding/json" "fmt" "image" "image/jpeg" "io" "math" "net/http" neturl "net/url" "path/filepath" "shudao-chat-go/utils" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/beego/beego/v2/server/web" ) type ShudaoOssController struct { web.Controller } // OSS配置信息 - 根据测试文件更新配置 var ( ossBucket = "gdsc-ai-aqzs" ossAccessKey = "fnyfi2f368pbic74d8ll" ossSecretKey = "jgqwk7sirqlz2602x2k7yx2eor0vii19wah6ywlv" // 修正SecretKey ossEndpoint = "http://172.16.17.52:8060" // 添加http://前缀 ossRegion = "us-east-1" ) // 图片压缩配置 const ( // 目标文件大小(字节) TargetFileSize = 200 * 1024 // 200KB // 最大图片尺寸(像素)- 作为备选方案 MaxImageWidth = 1920 MaxImageHeight = 1080 // JPEG压缩质量范围 MinJPEGQuality = 10 // 最低质量 MaxJPEGQuality = 95 // 最高质量 // 是否启用图片压缩 EnableImageCompression = true ) // 上传响应结构 type UploadResponse struct { StatusCode int `json:"statusCode"` Message string `json:"message"` FileURL string `json:"fileUrl"` FileName string `json:"fileName"` FileSize int64 `json:"fileSize"` } // 获取S3会话 func getS3Session() (*session.Session, error) { // 检查时间同步 now := time.Now() utcNow := now.UTC() fmt.Printf("=== S3会话创建调试信息 ===\n") fmt.Printf("本地时间: %s\n", now.Format("2006-01-02 15:04:05")) fmt.Printf("UTC时间: %s\n", utcNow.Format("2006-01-02 15:04:05")) fmt.Printf("时间差: %v\n", now.Sub(utcNow)) fmt.Printf("Bucket: %s\n", ossBucket) fmt.Printf("Endpoint: %s\n", ossEndpoint) fmt.Printf("Region: %s\n", ossRegion) fmt.Printf("AccessKey: %s***\n", ossAccessKey[:8]) s3Config := &aws.Config{ Credentials: credentials.NewStaticCredentials(ossAccessKey, ossSecretKey, ""), Endpoint: aws.String(ossEndpoint), Region: aws.String(ossRegion), S3ForcePathStyle: aws.Bool(true), // 使用路径样式而不是虚拟主机样式 DisableSSL: aws.Bool(true), // 如果endpoint是http则禁用SSL // 添加更多配置选项 LogLevel: aws.LogLevel(aws.LogDebug), // 启用调试日志 // 其他配置选项 MaxRetries: aws.Int(3), // 其他配置选项 } // 创建会话 sess, err := session.NewSession(s3Config) if err != nil { return nil, err } // 验证凭据 _, err = sess.Config.Credentials.Get() if err != nil { return nil, fmt.Errorf("凭据验证失败: %v", err) } return sess, nil } // 获取UTC时间同步的S3会话(根据测试文件优化配置) func getUTCS3Session() (*session.Session, error) { // 强制使用UTC时间 utcNow := time.Now().UTC() fmt.Printf("=== UTC S3会话创建调试信息 ===\n") fmt.Printf("强制使用UTC时间: %s\n", utcNow.Format("2006-01-02 15:04:05")) fmt.Printf("Bucket: %s\n", ossBucket) fmt.Printf("Endpoint: %s\n", ossEndpoint) fmt.Printf("Region: %s\n", ossRegion) fmt.Printf("AccessKey: %s***\n", ossAccessKey[:8]) // 创建S3配置 - 使用与测试文件相同的配置 s3Config := &aws.Config{ Credentials: credentials.NewStaticCredentials(ossAccessKey, ossSecretKey, ""), Endpoint: aws.String(ossEndpoint), Region: aws.String(ossRegion), S3ForcePathStyle: aws.Bool(true), // 强制使用路径样式(OSS兼容性需要) // 移除DisableSSL,因为endpoint已经包含http:// // 移除LogLevel,减少调试输出 // 移除MaxRetries,使用默认值 // 移除S3DisableContentMD5Validation,使用默认值 } // 创建会话 sess, err := session.NewSession(s3Config) if err != nil { return nil, err } // 验证凭据 _, err = sess.Config.Credentials.Get() if err != nil { return nil, fmt.Errorf("凭据验证失败: %v", err) } return sess, nil } // 判断是否为图片文件 func isImageFile(ext string) bool { imageExts := map[string]bool{ ".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".bmp": true, ".webp": true, ".tiff": true, ".svg": true, ".ico": true, } return imageExts[ext] } // 图片上传接口 func (c *ShudaoOssController) UploadImage() { c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*") c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type") if c.Ctx.Request.Method == "OPTIONS" { c.Ctx.ResponseWriter.WriteHeader(200) return } // 获取上传的图片文件 file, header, err := c.GetFile("image") if err != nil { c.Data["json"] = UploadResponse{ StatusCode: 400, Message: "获取上传图片失败: " + err.Error(), } c.ServeJSON() return } defer file.Close() // 检查文件扩展名 ext := strings.ToLower(filepath.Ext(header.Filename)) if !isImageFile(ext) { c.Data["json"] = UploadResponse{ StatusCode: 400, Message: "不支持的文件格式,请上传图片文件(jpg, png, gif, bmp, webp等)", } c.ServeJSON() return } // 图片文件大小限制(10MB) if header.Size > 10*1024*1024 { c.Data["json"] = UploadResponse{ StatusCode: 400, Message: "图片文件大小超过限制(10MB)", } c.ServeJSON() return } // 生成图片文件名(使用UTC时间) utcNow := time.Now().UTC() timestamp := utcNow.Unix() // 压缩后的图片统一使用.jpg扩展名 fileName := fmt.Sprintf("images/%d/%s_%d.jpg", utcNow.Year(), utcNow.Format("0102"), timestamp) // 读取图片内容 fileBytes, err := io.ReadAll(file) if err != nil { c.Data["json"] = UploadResponse{ StatusCode: 500, Message: "读取图片内容失败: " + err.Error(), } c.ServeJSON() return } // 压缩图片 if EnableImageCompression { fmt.Printf("开始压缩图片到200KB以下...\n") compressedBytes, err := compressImage(fileBytes, MaxImageWidth, MaxImageHeight, 0) // 参数不再使用 if err != nil { fmt.Printf("图片压缩失败,使用原始图片: %v\n", err) // 压缩失败时使用原始图片 } else { fmt.Printf("图片压缩完成,最终大小: %.2f KB\n", float64(len(compressedBytes))/1024) fileBytes = compressedBytes } } else { fmt.Printf("图片压缩已禁用,使用原始图片\n") } // 获取UTC时间同步的S3会话(解决时区问题) sess, err := getUTCS3Session() if err != nil { c.Data["json"] = UploadResponse{ StatusCode: 500, Message: "创建S3会话失败: " + err.Error(), } c.ServeJSON() return } // 创建S3服务 s3Client := s3.New(sess) // 打印上传信息 fmt.Printf("正在上传图片: %s\n", fileName) fmt.Printf("文件大小: %.2f KB\n", float64(len(fileBytes))/1024) fmt.Printf("ContentType: %s\n", header.Header.Get("Content-Type")) // 上传图片到S3 - 使用与测试文件相同的上传方式 _, err = s3Client.PutObject(&s3.PutObjectInput{ Bucket: aws.String(ossBucket), Key: aws.String(fileName), Body: aws.ReadSeekCloser(strings.NewReader(string(fileBytes))), // 使用与测试文件相同的方式 ACL: aws.String("public-read"), }) if err != nil { fmt.Printf("上传图片失败: %v\n", err) c.Data["json"] = UploadResponse{ StatusCode: 500, Message: "上传图片到OSS失败: " + err.Error(), } c.ServeJSON() return } // // 生成预签名URL(1小时有效期) // req, _ := s3Client.GetObjectRequest(&s3.GetObjectInput{ // Bucket: aws.String(ossBucket), // Key: aws.String(fileName), // }) // presignedURL, err := req.Presign(24 * time.Hour) // if err != nil { // fmt.Printf("生成预签名URL失败: %v\n", err) // // 如果预签名URL生成失败,使用简单URL作为备选 // imageURL := fmt.Sprintf("%s/%s", ossEndpoint, fileName) // c.Data["json"] = UploadResponse{ // StatusCode: 200, // Message: "图片上传成功,但预签名URL生成失败", // FileURL: imageURL, // FileName: fileName, // FileSize: header.Size, // } // c.ServeJSON() // return // } permanentURL := fmt.Sprintf("%s/%s/%s", ossEndpoint, ossBucket, fileName) // 使用代理接口包装URL,前端需要预览图片 proxyURL := utils.GetProxyURL(permanentURL) fmt.Printf("图片上传成功: %s\n", fileName) fmt.Printf("文件URL: %s\n", permanentURL) fmt.Printf("代理URL: %s\n", proxyURL) c.Data["json"] = UploadResponse{ StatusCode: 200, Message: "图片上传成功", FileURL: proxyURL, FileName: fileName, FileSize: int64(len(fileBytes)), // 使用压缩后的文件大小 } c.ServeJSON() } // 上传PPTjson文件 func (c *ShudaoOssController) UploadPPTJson() { c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*") c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type") if c.Ctx.Request.Method == "OPTIONS" { c.Ctx.ResponseWriter.WriteHeader(200) return } // 获取上传的JSON文件 file, header, err := c.GetFile("json") if err != nil { c.Data["json"] = UploadResponse{ StatusCode: 400, Message: "获取上传JSON文件失败: " + err.Error(), } c.ServeJSON() return } defer file.Close() // 检查文件扩展名 ext := strings.ToLower(filepath.Ext(header.Filename)) if ext != ".json" { c.Data["json"] = UploadResponse{ StatusCode: 400, Message: "不支持的文件格式,请上传JSON文件(.json)", } c.ServeJSON() return } // JSON文件大小限制(50MB) if header.Size > 50*1024*1024 { c.Data["json"] = UploadResponse{ StatusCode: 400, Message: "JSON文件大小超过限制(50MB)", } c.ServeJSON() return } // 生成JSON文件名(使用UTC时间) utcNow := time.Now().UTC() timestamp := utcNow.Unix() fileName := fmt.Sprintf("json/%d/%s_%d%s", utcNow.Year(), utcNow.Format("0102"), timestamp, ext) // 读取JSON内容 fileBytes, err := io.ReadAll(file) if err != nil { c.Data["json"] = UploadResponse{ StatusCode: 500, Message: "读取JSON内容失败: " + err.Error(), } c.ServeJSON() return } // 验证JSON格式 var jsonData interface{} if err := json.Unmarshal(fileBytes, &jsonData); err != nil { c.Data["json"] = UploadResponse{ StatusCode: 400, Message: "JSON格式无效: " + err.Error(), } c.ServeJSON() return } // 获取UTC时间同步的S3会话 sess, err := getUTCS3Session() if err != nil { c.Data["json"] = UploadResponse{ StatusCode: 500, Message: "创建S3会话失败: " + err.Error(), } c.ServeJSON() return } // 创建S3服务 s3Client := s3.New(sess) // 打印上传信息 fmt.Printf("正在上传JSON文件: %s\n", fileName) fmt.Printf("文件大小: %.2f KB\n", float64(len(fileBytes))/1024) fmt.Printf("ContentType: %s\n", header.Header.Get("Content-Type")) // 上传JSON到S3 _, err = s3Client.PutObject(&s3.PutObjectInput{ Bucket: aws.String(ossBucket), Key: aws.String(fileName), Body: aws.ReadSeekCloser(strings.NewReader(string(fileBytes))), ACL: aws.String("public-read"), ContentType: aws.String("application/json"), }) if err != nil { fmt.Printf("上传JSON文件失败: %v\n", err) c.Data["json"] = UploadResponse{ StatusCode: 500, Message: "上传JSON文件到OSS失败: " + err.Error(), } c.ServeJSON() return } // 生成永久URL permanentURL := fmt.Sprintf("%s/%s/%s", ossEndpoint, ossBucket, fileName) // 使用代理接口包装URL,前端需要访问文件 proxyURL := utils.GetProxyURL(permanentURL) fmt.Printf("JSON文件上传成功: %s\n", fileName) fmt.Printf("文件URL: %s\n", permanentURL) fmt.Printf("代理URL: %s\n", proxyURL) c.Data["json"] = UploadResponse{ StatusCode: 200, Message: "JSON文件上传成功", FileURL: proxyURL, FileName: fileName, FileSize: header.Size, } c.ServeJSON() } // ParseOSS OSS代理解析接口,用于代理转发OSS URL请求 func (c *ShudaoOssController) ParseOSS() { // 设置CORS头 c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*") c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS") c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type") // 处理OPTIONS预检请求 if c.Ctx.Request.Method == "OPTIONS" { c.Ctx.ResponseWriter.WriteHeader(200) return } // 获取URL参数(加密的) encryptedURL := c.GetString("url") if encryptedURL == "" { c.Ctx.ResponseWriter.WriteHeader(400) c.Ctx.WriteString("缺少url参数") return } // 解密URL decryptedURL, err := utils.DecryptURL(encryptedURL) if err != nil { fmt.Printf("URL解密失败: %v, 加密URL: %s\n", err, encryptedURL) c.Ctx.ResponseWriter.WriteHeader(400) c.Ctx.WriteString("URL解密失败: " + err.Error()) return } // URL解码,处理可能的编码问题 decodedURL, err := neturl.QueryUnescape(decryptedURL) if err != nil { fmt.Printf("URL解码失败: %v, 解密后URL: %s\n", err, decryptedURL) // 如果解码失败,使用解密后的URL decodedURL = decryptedURL } var actualOSSURL string // 检查是否是代理URL格式(包含?url=参数) if strings.Contains(decodedURL, "?url=") { // 解析代理URL,提取实际的OSS URL parsedProxyURL, err := neturl.Parse(decodedURL) if err != nil { fmt.Printf("代理URL解析失败: %v, 解码后URL: %s\n", err, decodedURL) c.Ctx.ResponseWriter.WriteHeader(400) c.Ctx.WriteString("代理URL格式无效: " + err.Error()) return } // 获取实际的OSS URL actualOSSURL = parsedProxyURL.Query().Get("url") if actualOSSURL == "" { fmt.Printf("代理URL中缺少url参数: %s\n", decodedURL) c.Ctx.ResponseWriter.WriteHeader(400) c.Ctx.WriteString("代理URL中缺少url参数") return } } else { // 直接使用传入的URL作为OSS URL actualOSSURL = decodedURL fmt.Printf("检测到直接OSS URL: %s\n", actualOSSURL) } // 验证实际OSS URL格式 parsedOSSURL, err := neturl.Parse(actualOSSURL) if err != nil { fmt.Printf("OSS URL解析失败: %v, OSS URL: %s\n", err, actualOSSURL) c.Ctx.ResponseWriter.WriteHeader(400) c.Ctx.WriteString("OSS URL格式无效: " + err.Error()) return } if parsedOSSURL.Scheme == "" { fmt.Printf("OSS URL缺少协议方案: %s\n", actualOSSURL) c.Ctx.ResponseWriter.WriteHeader(400) c.Ctx.WriteString("OSS URL缺少协议方案") return } fmt.Printf("代理请求 - 加密URL: %s, 解密后URL: %s, 解码后URL: %s, 实际OSS URL: %s, 协议: %s\n", encryptedURL, decryptedURL, decodedURL, actualOSSURL, parsedOSSURL.Scheme) // 创建HTTP客户端,设置超时时间 client := &http.Client{ Timeout: 30 * time.Second, } // 发送GET请求到实际的OSS URL resp, err := client.Get(actualOSSURL) if err != nil { c.Ctx.ResponseWriter.WriteHeader(502) c.Ctx.WriteString("无法连接到OSS: " + err.Error()) return } defer resp.Body.Close() // 检查HTTP状态码 if resp.StatusCode != http.StatusOK { c.Ctx.ResponseWriter.WriteHeader(resp.StatusCode) c.Ctx.WriteString(fmt.Sprintf("OSS返回错误: %d", resp.StatusCode)) return } // 读取响应内容 content, err := io.ReadAll(resp.Body) if err != nil { c.Ctx.ResponseWriter.WriteHeader(500) c.Ctx.WriteString("读取OSS响应失败: " + err.Error()) return } // 获取原始的content-type contentType := resp.Header.Get("content-type") if contentType == "" { contentType = "application/octet-stream" } // 如果OSS返回的是binary/octet-stream或application/octet-stream, // 尝试根据URL文件扩展名推断正确的MIME类型 if contentType == "binary/octet-stream" || contentType == "application/octet-stream" { // 解析URL获取文件路径 parsedURL, err := neturl.Parse(actualOSSURL) if err == nil { filePath := parsedURL.Path // URL解码,处理中文文件名 filePath, err = neturl.QueryUnescape(filePath) if err == nil { // 根据文件扩展名猜测MIME类型 if strings.HasSuffix(strings.ToLower(filePath), ".jpg") || strings.HasSuffix(strings.ToLower(filePath), ".jpeg") { contentType = "image/jpeg" } else if strings.HasSuffix(strings.ToLower(filePath), ".png") { contentType = "image/png" } else if strings.HasSuffix(strings.ToLower(filePath), ".gif") { contentType = "image/gif" } else if strings.HasSuffix(strings.ToLower(filePath), ".pdf") { contentType = "application/pdf" } else if strings.HasSuffix(strings.ToLower(filePath), ".json") { contentType = "application/json" } else if strings.HasSuffix(strings.ToLower(filePath), ".txt") { contentType = "text/plain" } } } } // 设置响应头 c.Ctx.ResponseWriter.Header().Set("Content-Type", contentType) c.Ctx.ResponseWriter.Header().Set("Content-Length", fmt.Sprintf("%d", len(content))) // 转发重要的响应头 importantHeaders := []string{ "content-disposition", "cache-control", "etag", "last-modified", "accept-ranges", } for _, header := range importantHeaders { if value := resp.Header.Get(header); value != "" { c.Ctx.ResponseWriter.Header().Set(header, value) } } // 写入响应内容 c.Ctx.ResponseWriter.WriteHeader(200) c.Ctx.ResponseWriter.Write(content) } // compressImage 压缩图片到目标大小 func compressImage(imageData []byte, maxWidth, maxHeight int, quality int) ([]byte, error) { // 解码图片 img, format, err := image.Decode(bytes.NewReader(imageData)) if err != nil { return nil, fmt.Errorf("解码图片失败: %v", err) } // 获取原始尺寸 bounds := img.Bounds() originalWidth := bounds.Dx() originalHeight := bounds.Dy() originalSize := len(imageData) fmt.Printf("原始图片: %dx%d, 格式: %s, 大小: %.2f KB\n", originalWidth, originalHeight, format, float64(originalSize)/1024) // 如果原始文件已经小于目标大小,直接返回 if originalSize <= TargetFileSize { fmt.Printf("文件已小于目标大小,无需压缩\n") return imageData, nil } // 尝试不同的压缩策略 compressedData, err := compressToTargetSize(img, originalSize) if err != nil { return nil, err } finalSize := len(compressedData) compressionRatio := float64(finalSize) / float64(originalSize) * 100 fmt.Printf("压缩完成: %.2f KB -> %.2f KB (压缩率: %.1f%%)\n", float64(originalSize)/1024, float64(finalSize)/1024, compressionRatio) return compressedData, nil } // compressToTargetSize 压缩到目标文件大小 func compressToTargetSize(img image.Image, originalSize int) ([]byte, error) { bounds := img.Bounds() originalWidth := bounds.Dx() originalHeight := bounds.Dy() // 策略1: 先尝试调整质量,不改变尺寸 fmt.Printf("策略1: 调整质量压缩...\n") compressedData, err := compressByQuality(img, originalSize) if err == nil && len(compressedData) <= TargetFileSize { fmt.Printf("质量压缩成功,达到目标大小\n") return compressedData, nil } // 策略2: 如果质量压缩不够,尝试缩小尺寸 fmt.Printf("策略2: 尺寸+质量压缩...\n") // 计算需要缩小的比例 targetRatio := float64(TargetFileSize) / float64(originalSize) sizeRatio := math.Sqrt(targetRatio * 0.8) // 留一些余量给质量调整 newWidth := int(float64(originalWidth) * sizeRatio) newHeight := int(float64(originalHeight) * sizeRatio) // 确保最小尺寸 if newWidth < 100 { newWidth = 100 } if newHeight < 100 { newHeight = 100 } fmt.Printf("调整尺寸: %dx%d -> %dx%d\n", originalWidth, originalHeight, newWidth, newHeight) // 调整图片尺寸 resizedImg := resizeImage(img, newWidth, newHeight) // 再次尝试质量压缩 return compressByQuality(resizedImg, originalSize) } // compressByQuality 通过调整质量压缩图片 func compressByQuality(img image.Image, originalSize int) ([]byte, error) { var bestResult []byte var bestSize int = originalSize // 从高质量到低质量尝试 qualities := []int{85, 70, 60, 50, 40, 30, 25, 20, 15, 10} for _, quality := range qualities { var buf bytes.Buffer if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil { continue } currentSize := buf.Len() fmt.Printf(" 质量 %d: %.2f KB\n", quality, float64(currentSize)/1024) // 如果达到目标大小,直接返回 if currentSize <= TargetFileSize { fmt.Printf(" 达到目标大小,质量: %d\n", quality) return buf.Bytes(), nil } // 记录最佳结果 if currentSize < bestSize { bestSize = currentSize bestResult = buf.Bytes() } } // 如果没有达到目标大小,返回最佳结果 if bestResult != nil { fmt.Printf(" 未达到目标大小,使用最佳结果: %.2f KB\n", float64(bestSize)/1024) return bestResult, nil } return nil, fmt.Errorf("压缩失败") } // resizeImage 调整图片尺寸 func resizeImage(img image.Image, newWidth, newHeight int) image.Image { // 创建新的图片 resized := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight)) // 简单的最近邻插值缩放 bounds := img.Bounds() for y := 0; y < newHeight; y++ { for x := 0; x < newWidth; x++ { // 计算原始图片中的对应位置 srcX := int(float64(x) * float64(bounds.Dx()) / float64(newWidth)) srcY := int(float64(y) * float64(bounds.Dy()) / float64(newHeight)) // 确保不超出边界 if srcX >= bounds.Dx() { srcX = bounds.Dx() - 1 } if srcY >= bounds.Dy() { srcY = bounds.Dy() - 1 } resized.Set(x, y, img.At(bounds.Min.X+srcX, bounds.Min.Y+srcY)) } } return resized }