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.

60 lines
1.3 KiB

  1. package operation
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "path/filepath"
  7. _ "fmt"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "mime"
  12. "mime/multipart"
  13. "net/http"
  14. )
  15. type UploadResult struct {
  16. Size int
  17. Error string
  18. }
  19. func Upload(uploadUrl string, filename string, reader io.Reader) (*UploadResult, error) {
  20. body_buf := bytes.NewBufferString("")
  21. body_writer := multipart.NewWriter(body_buf)
  22. file_writer, err := body_writer.CreateFormFile("file", filename)
  23. if err != nil {
  24. log.Println("error creating form file", err)
  25. return nil, err
  26. }
  27. if _, err = io.Copy(file_writer, reader); err != nil {
  28. log.Println("error copying data", err)
  29. return nil, err
  30. }
  31. content_type := mime.TypeByExtension(filepath.Ext(filename))
  32. content_type := body_writer.FormDataContentType()
  33. if err = body_writer.Close(); err != nil {
  34. log.Println("error closing body", err)
  35. return nil, err
  36. }
  37. resp, err := http.Post(uploadUrl, content_type, body_buf)
  38. if err != nil {
  39. log.Println("failing to upload to", uploadUrl)
  40. return nil, err
  41. }
  42. defer resp.Body.Close()
  43. resp_body, err := ioutil.ReadAll(resp.Body)
  44. if err != nil {
  45. return nil, err
  46. }
  47. var ret UploadResult
  48. err = json.Unmarshal(resp_body, &ret)
  49. if err != nil {
  50. log.Println("failing to read upload resonse", uploadUrl, resp_body)
  51. return nil, err
  52. }
  53. if ret.Error != "" {
  54. return nil, errors.New(ret.Error)
  55. }
  56. return &ret, nil
  57. }