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.

50 lines
1.4 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 servers
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/qiniu/api.v7/auth/qbox"
  6. "github.com/qiniu/api.v7/storage"
  7. "mime/multipart"
  8. "time"
  9. )
  10. var accessKey string = "25j8dYBZ2wui***************62b8xiFguwxzZ" // 你在七牛云的accessKey
  11. var secretKey string = "pgdbqEsf7ooZ***************_VecFXPDeG5JY" // 你在七牛云的secretKey
  12. // 接收两个参数 一个文件流 一个 bucket 你的七牛云标准空间的名字
  13. func Upload(file *multipart.FileHeader, bucket string, urlPath string) (err error, path string) {
  14. putPolicy := storage.PutPolicy{
  15. Scope: bucket,
  16. }
  17. mac := qbox.NewMac(accessKey, secretKey)
  18. upToken := putPolicy.UploadToken(mac)
  19. cfg := storage.Config{}
  20. // 空间对应的机房
  21. cfg.Zone = &storage.ZoneHuadong
  22. // 是否使用https域名
  23. cfg.UseHTTPS = false
  24. // 上传是否使用CDN上传加速
  25. cfg.UseCdnDomains = false
  26. formUploader := storage.NewFormUploader(&cfg)
  27. ret := storage.PutRet{}
  28. putExtra := storage.PutExtra{
  29. Params: map[string]string{
  30. "x:name": "github logo",
  31. },
  32. }
  33. f, e := file.Open()
  34. if e != nil {
  35. fmt.Println(e)
  36. return e, ""
  37. }
  38. dataLen := file.Size
  39. fileKey := fmt.Sprintf("%d%s", time.Now().Unix(), file.Filename) // 文件名格式 自己可以改 建议保证唯一性
  40. err = formUploader.Put(context.Background(), &ret, upToken, fileKey, f, dataLen, &putExtra)
  41. if err != nil {
  42. fmt.Println(err)
  43. //qmlog.QMLog.Info(err)
  44. return err, ""
  45. }
  46. return err, urlPath + "/" + ret.Key
  47. }