webdavuploader.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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/util"
  11. )
  12. type WebdavUploader struct {
  13. url string
  14. username string
  15. password string
  16. }
  17. func (u *WebdavUploader) Upload(pa string) (string, error) {
  18. client := http.Client{Timeout: time.Duration(10 * time.Second)}
  19. url, _ := url.Parse(u.url)
  20. url.Path = path.Join(url.Path, util.GetRandomString(20)+".png")
  21. imgData, err := ioutil.ReadFile(pa)
  22. req, err := http.NewRequest("PUT", url.String(), bytes.NewReader(imgData))
  23. res, err := client.Do(req)
  24. if err != nil {
  25. return "", err
  26. }
  27. if res.StatusCode != http.StatusCreated {
  28. body, _ := ioutil.ReadAll(res.Body)
  29. return "", fmt.Errorf("Failed to upload image. Returned statuscode %v body %s", res.StatusCode, body)
  30. }
  31. return url.String(), nil
  32. }
  33. func NewWebdavImageUploader(url, username, passwrod string) (*WebdavUploader, error) {
  34. return &WebdavUploader{
  35. url: url,
  36. username: username,
  37. password: passwrod,
  38. }, nil
  39. }