webdavuploader.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package imguploader
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "path"
  9. "github.com/grafana/grafana/pkg/util"
  10. )
  11. type WebdavUploader struct {
  12. url string
  13. username string
  14. password string
  15. }
  16. func (u *WebdavUploader) Upload(pa string) (string, error) {
  17. url, _ := url.Parse(u.url)
  18. url.Path = path.Join(url.Path, util.GetRandomString(20)+".png")
  19. imgData, err := ioutil.ReadFile(pa)
  20. req, err := http.NewRequest("PUT", url.String(), bytes.NewReader(imgData))
  21. if u.username != "" {
  22. req.SetBasicAuth(u.username, u.password)
  23. }
  24. res, err := http.DefaultClient.Do(req)
  25. if err != nil {
  26. return "", err
  27. }
  28. if res.StatusCode != http.StatusCreated {
  29. body, _ := ioutil.ReadAll(res.Body)
  30. return "", fmt.Errorf("Failed to upload image. Returned statuscode %v body %s", res.StatusCode, body)
  31. }
  32. return url.String(), nil
  33. }
  34. func NewWebdavImageUploader(url, username, passwrod string) (*WebdavUploader, error) {
  35. return &WebdavUploader{
  36. url: url,
  37. username: username,
  38. password: passwrod,
  39. }, nil
  40. }