webdavuploader.go 1.1 KB

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