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.

69 lines
1.7 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. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  22. func Upload(uploadUrl string, filename string, reader io.Reader, isGzipped bool) (*UploadResult, error) {
  23. body_buf := bytes.NewBufferString("")
  24. body_writer := multipart.NewWriter(body_buf)
  25. h := make(textproto.MIMEHeader)
  26. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  27. h.Set("Content-Type", mime.TypeByExtension(strings.ToLower(filepath.Ext(filename))))
  28. if isGzipped {
  29. h.Set("Content-Encoding", "gzip")
  30. }
  31. file_writer, err := body_writer.CreatePart(h)
  32. if err != nil {
  33. log.Println("error creating form file", err)
  34. return nil, err
  35. }
  36. if _, err = io.Copy(file_writer, reader); err != nil {
  37. log.Println("error copying data", err)
  38. return nil, err
  39. }
  40. content_type := body_writer.FormDataContentType()
  41. if err = body_writer.Close(); err != nil {
  42. log.Println("error closing body", err)
  43. return nil, err
  44. }
  45. resp, err := http.Post(uploadUrl, content_type, body_buf)
  46. if err != nil {
  47. log.Println("failing to upload to", uploadUrl)
  48. return nil, err
  49. }
  50. defer resp.Body.Close()
  51. resp_body, err := ioutil.ReadAll(resp.Body)
  52. if err != nil {
  53. return nil, err
  54. }
  55. var ret UploadResult
  56. err = json.Unmarshal(resp_body, &ret)
  57. if err != nil {
  58. log.Println("failing to read upload resonse", uploadUrl, resp_body)
  59. return nil, err
  60. }
  61. if ret.Error != "" {
  62. return nil, errors.New(ret.Error)
  63. }
  64. return &ret, nil
  65. }