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.

72 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, mtype string) (*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. if mtype == "" {
  28. mtype = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  29. }
  30. h.Set("Content-Type", mtype)
  31. if isGzipped {
  32. h.Set("Content-Encoding", "gzip")
  33. }
  34. file_writer, err := body_writer.CreatePart(h)
  35. if err != nil {
  36. log.Println("error creating form file", err)
  37. return nil, err
  38. }
  39. if _, err = io.Copy(file_writer, reader); err != nil {
  40. log.Println("error copying data", err)
  41. return nil, err
  42. }
  43. content_type := body_writer.FormDataContentType()
  44. if err = body_writer.Close(); err != nil {
  45. log.Println("error closing body", err)
  46. return nil, err
  47. }
  48. resp, err := http.Post(uploadUrl, content_type, body_buf)
  49. if err != nil {
  50. log.Println("failing to upload to", uploadUrl)
  51. return nil, err
  52. }
  53. defer resp.Body.Close()
  54. resp_body, err := ioutil.ReadAll(resp.Body)
  55. if err != nil {
  56. return nil, err
  57. }
  58. var ret UploadResult
  59. err = json.Unmarshal(resp_body, &ret)
  60. if err != nil {
  61. log.Println("failing to read upload resonse", uploadUrl, resp_body)
  62. return nil, err
  63. }
  64. if ret.Error != "" {
  65. return nil, errors.New(ret.Error)
  66. }
  67. return &ret, nil
  68. }