qiniu.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package utils
  2. import (
  3. "fmt"
  4. "github.com/google/uuid"
  5. "github.com/qiniu/go-sdk/v7/auth/qbox"
  6. "github.com/qiniu/go-sdk/v7/storage"
  7. "log"
  8. "project_management/global"
  9. "strconv"
  10. "time"
  11. )
  12. // GetToken 获取上传凭证
  13. func GetToken(T_suffix string) string {
  14. mac := qbox.NewMac(global.QiniuSetting.AccessKeyID, global.QiniuSetting.AccessKeySecret)
  15. Tokey := strconv.FormatInt(time.Now().Unix(), 10) + uuid.NewString()
  16. if len(T_suffix) == 0 {
  17. T_suffix = "png"
  18. }
  19. // 构建表单上传的对象
  20. putPolicy := storage.PutPolicy{
  21. Scope: global.QiniuSetting.BucketName,
  22. Expires: 7200,
  23. InsertOnly: 1,
  24. ForceSaveKey: true,
  25. ReturnBody: `{"key":"` + global.QiniuSetting.Endpoint + `/$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)"}`, SaveKey: "UpImage/" + Tokey + "." + T_suffix,
  26. MimeLimit: "image/*;application/pdf;application/octet-stream;application/zip;application/x-tar",
  27. FsizeLimit: 1024 * 1024 * 100,
  28. }
  29. upToken := putPolicy.UploadToken(mac)
  30. return upToken
  31. }
  32. // DeleteFiles 删除文件
  33. func DeleteFiles(accessKey, secretKey, bucket string, files []string) {
  34. cfg := storage.Config{
  35. Zone: &storage.ZoneHuanan,
  36. }
  37. bucketManager := storage.NewBucketManager(qbox.NewMac(accessKey, secretKey), &cfg)
  38. ops := make([]string, len(files))
  39. for i, file := range files {
  40. ops[i] = storage.URIDelete(bucket, file)
  41. }
  42. _, err := bucketManager.Batch(ops)
  43. if err != nil {
  44. log.Fatal("Batch delete failed:", err)
  45. }
  46. fmt.Println("Files deleted successfully.")
  47. }
  48. // GetFileInfo 获取文件信息
  49. func GetFileInfo(accessKey, secretKey, bucket string, files []string) map[string]storage.FileInfo {
  50. mac := qbox.NewMac(accessKey, secretKey)
  51. cfg := storage.Config{
  52. Zone: &storage.ZoneHuadong,
  53. }
  54. bucketManager := storage.NewBucketManager(mac, &cfg)
  55. fileInfoMap := make(map[string]storage.FileInfo)
  56. for _, file := range files {
  57. fileInfo, err := bucketManager.Stat(bucket, file)
  58. if err != nil {
  59. log.Println("Get file info failed:", err)
  60. } else {
  61. fileInfoMap[file] = fileInfo
  62. }
  63. }
  64. return fileInfoMap
  65. }