You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.9 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package utils
  2. import (
  3. "context"
  4. "fmt"
  5. "gin-vue-admin/global"
  6. "github.com/qiniu/api.v7/auth/qbox"
  7. "github.com/qiniu/api.v7/storage"
  8. "mime/multipart"
  9. "time"
  10. )
  11. // 接收两个参数 一个文件流 一个 bucket 你的七牛云标准空间的名字
  12. func Upload(file *multipart.FileHeader) (err error, path string, key string) {
  13. putPolicy := storage.PutPolicy{
  14. Scope: global.GVA_CONFIG.Qiniu.Bucket,
  15. }
  16. mac := qbox.NewMac(global.GVA_CONFIG.Qiniu.AccessKey, global.GVA_CONFIG.Qiniu.SecretKey)
  17. upToken := putPolicy.UploadToken(mac)
  18. cfg := storage.Config{}
  19. // 空间对应的机房
  20. cfg.Zone = &storage.ZoneHuadong
  21. // 是否使用https域名
  22. cfg.UseHTTPS = false
  23. // 上传是否使用CDN上传加速
  24. cfg.UseCdnDomains = false
  25. formUploader := storage.NewFormUploader(&cfg)
  26. ret := storage.PutRet{}
  27. putExtra := storage.PutExtra{
  28. Params: map[string]string{
  29. "x:name": "github logo",
  30. },
  31. }
  32. f, e := file.Open()
  33. if e != nil {
  34. fmt.Println(e)
  35. return e, "", ""
  36. }
  37. dataLen := file.Size
  38. fileKey := fmt.Sprintf("%d%s", time.Now().Unix(), file.Filename) // 文件名格式 自己可以改 建议保证唯一性
  39. err = formUploader.Put(context.Background(), &ret, upToken, fileKey, f, dataLen, &putExtra)
  40. if err != nil {
  41. global.GVA_LOG.Error("upload file fail:", err)
  42. return err, "", ""
  43. }
  44. return err, global.GVA_CONFIG.Qiniu.ImgPath + "/" + ret.Key, ret.Key
  45. }
  46. func DeleteFile(key string) error {
  47. mac := qbox.NewMac(global.GVA_CONFIG.Qiniu.AccessKey, global.GVA_CONFIG.Qiniu.SecretKey)
  48. cfg := storage.Config{
  49. // 是否使用https域名进行资源管理
  50. UseHTTPS: false,
  51. }
  52. // 指定空间所在的区域,如果不指定将自动探测
  53. // 如果没有特殊需求,默认不需要指定
  54. //cfg.Zone=&storage.ZoneHuabei
  55. bucketManager := storage.NewBucketManager(mac, &cfg)
  56. err := bucketManager.Delete(global.GVA_CONFIG.Qiniu.Bucket, key)
  57. if err != nil {
  58. fmt.Println(err)
  59. return err
  60. }
  61. return nil
  62. }