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.

64 lines
1.5 KiB

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