add_data.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package tests
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/aws/aws-sdk-go/aws"
  13. "github.com/aws/aws-sdk-go/aws/credentials"
  14. "github.com/aws/aws-sdk-go/aws/session"
  15. "github.com/aws/aws-sdk-go/service/s3"
  16. )
  17. // OSS配置信息
  18. var (
  19. ossBucket = "gdsc-ai-aqzs"
  20. ossAccessKey = "fnyfi2f368pbic74d8ll"
  21. ossSecretKey = "jgqwk7sirqlz2602x2k7yx2eor0vii19wah6ywlv"
  22. ossEndpoint = "http://172.16.17.52:8060"
  23. ossRegion = "us-east-1"
  24. )
  25. // 简单测试函数
  26. func TestSimple(t *testing.T) {
  27. t.Logf("这是一个简单测试")
  28. t.Logf("测试日志输出")
  29. }
  30. // 批量上传图片测试函数
  31. func TestBatchUploadImages(t *testing.T) {
  32. t.Logf("=== 开始批量上传图片测试 ===")
  33. // 先测试一个简单的日志输出
  34. t.Logf("测试日志输出正常")
  35. // 设置图片文件夹路径
  36. imageFolder := "C:/Users/allen/Desktop/隐患识别图/正确图片"
  37. t.Logf("目标文件夹: %s", imageFolder)
  38. // 检查文件夹是否存在
  39. if _, err := os.Stat(imageFolder); os.IsNotExist(err) {
  40. t.Fatalf("文件夹不存在: %s", imageFolder)
  41. }
  42. t.Logf("文件夹存在,开始扫描...")
  43. // 获取所有图片文件
  44. imageFiles, err := getImageFiles(imageFolder)
  45. if err != nil {
  46. t.Fatalf("获取图片文件失败: %v", err)
  47. }
  48. t.Logf("找到 %d 个图片文件", len(imageFiles))
  49. // 创建S3会话
  50. sess, err := createS3Session()
  51. if err != nil {
  52. t.Fatalf("创建S3会话失败: %v", err)
  53. }
  54. s3Client := s3.New(sess)
  55. // 处理每个图片文件(只处理前5个文件进行测试)
  56. successCount := 0
  57. errorCount := 0
  58. // 限制处理文件数量
  59. maxFiles := 5
  60. if len(imageFiles) > maxFiles {
  61. imageFiles = imageFiles[:maxFiles]
  62. t.Logf("为了测试,只处理前 %d 个文件", maxFiles)
  63. }
  64. for i, imageFile := range imageFiles {
  65. t.Logf("处理文件 %d/%d: %s", i+1, len(imageFiles), filepath.Base(imageFile))
  66. // 提取文件名中的序号
  67. fileID, err := extractIDFromFilename(filepath.Base(imageFile))
  68. if err != nil {
  69. t.Logf(" 错误: 无法提取序号 - %v", err)
  70. errorCount++
  71. continue
  72. }
  73. t.Logf(" 提取的序号: %d", fileID)
  74. // 暂时跳过数据库检查,直接测试OSS上传
  75. t.Logf(" 跳过数据库检查,直接测试OSS上传")
  76. // 上传图片到OSS
  77. imageURL, err := uploadImageToOSS(s3Client, imageFile, fileID)
  78. if err != nil {
  79. t.Logf(" 错误: 上传图片失败 - %v", err)
  80. errorCount++
  81. continue
  82. }
  83. t.Logf(" 图片上传成功: %s", imageURL)
  84. // 暂时跳过数据库更新
  85. t.Logf(" 跳过数据库更新")
  86. successCount++
  87. // 添加延迟避免请求过于频繁
  88. time.Sleep(100 * time.Millisecond)
  89. }
  90. t.Logf("处理完成!")
  91. t.Logf("成功处理: %d 个文件", successCount)
  92. t.Logf("处理失败: %d 个文件", errorCount)
  93. }
  94. // 获取文件夹中的所有图片文件
  95. func getImageFiles(folderPath string) ([]string, error) {
  96. var imageFiles []string
  97. // 支持的图片格式
  98. imageExts := map[string]bool{
  99. ".jpg": true,
  100. ".jpeg": true,
  101. ".png": true,
  102. ".gif": true,
  103. ".bmp": true,
  104. ".webp": true,
  105. ".tiff": true,
  106. ".svg": true,
  107. ".ico": true,
  108. }
  109. err := filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
  110. if err != nil {
  111. return err
  112. }
  113. if !info.IsDir() {
  114. ext := strings.ToLower(filepath.Ext(path))
  115. if imageExts[ext] {
  116. imageFiles = append(imageFiles, path)
  117. }
  118. }
  119. return nil
  120. })
  121. return imageFiles, err
  122. }
  123. // 从文件名中提取序号
  124. func extractIDFromFilename(filename string) (int, error) {
  125. // 移除文件扩展名
  126. nameWithoutExt := strings.TrimSuffix(filename, filepath.Ext(filename))
  127. // 使用正则表达式提取开头的数字
  128. re := regexp.MustCompile(`^(\d+)`)
  129. matches := re.FindStringSubmatch(nameWithoutExt)
  130. if len(matches) < 2 {
  131. return 0, fmt.Errorf("文件名中未找到数字序号: %s", filename)
  132. }
  133. id, err := strconv.Atoi(matches[1])
  134. if err != nil {
  135. return 0, fmt.Errorf("无法解析序号: %s", matches[1])
  136. }
  137. return id, nil
  138. }
  139. // 创建S3会话
  140. func createS3Session() (*session.Session, error) {
  141. s3Config := &aws.Config{
  142. Credentials: credentials.NewStaticCredentials(ossAccessKey, ossSecretKey, ""),
  143. Endpoint: aws.String(ossEndpoint),
  144. Region: aws.String(ossRegion),
  145. S3ForcePathStyle: aws.Bool(true),
  146. }
  147. sess, err := session.NewSession(s3Config)
  148. if err != nil {
  149. return nil, err
  150. }
  151. // 验证凭据
  152. _, err = sess.Config.Credentials.Get()
  153. if err != nil {
  154. return nil, fmt.Errorf("凭据验证失败: %v", err)
  155. }
  156. return sess, nil
  157. }
  158. // 上传图片到OSS
  159. func uploadImageToOSS(s3Client *s3.S3, imagePath string, fileID int) (string, error) {
  160. // 打开图片文件
  161. file, err := os.Open(imagePath)
  162. if err != nil {
  163. return "", err
  164. }
  165. defer file.Close()
  166. // 生成文件名
  167. ext := filepath.Ext(imagePath)
  168. fileName := fmt.Sprintf("batch_upload/%d_%d%s",
  169. time.Now().Unix(), fileID, ext)
  170. // 读取文件内容
  171. fileBytes, err := io.ReadAll(file)
  172. if err != nil {
  173. return "", err
  174. }
  175. // 上传到S3
  176. _, err = s3Client.PutObject(&s3.PutObjectInput{
  177. Bucket: aws.String(ossBucket),
  178. Key: aws.String(fileName),
  179. Body: aws.ReadSeekCloser(strings.NewReader(string(fileBytes))),
  180. ACL: aws.String("public-read"),
  181. })
  182. if err != nil {
  183. return "", err
  184. }
  185. // 生成访问URL
  186. imageURL := fmt.Sprintf("%s/%s/%s", ossEndpoint, ossBucket, fileName)
  187. return imageURL, nil
  188. }