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.

80 lines
2.1 KiB

12 years ago
  1. package operation
  2. import (
  3. "bytes"
  4. "code.google.com/p/weed-fs/go/glog"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  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. return upload_content(uploadUrl, func(w io.Writer) (err error) {
  24. _, err = io.Copy(w, reader)
  25. return
  26. }, filename, isGzipped, mtype)
  27. }
  28. func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error, filename string, isGzipped bool, mtype string) (*UploadResult, error) {
  29. body_buf := bytes.NewBufferString("")
  30. body_writer := multipart.NewWriter(body_buf)
  31. h := make(textproto.MIMEHeader)
  32. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  33. if mtype == "" {
  34. mtype = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  35. }
  36. if mtype != "" {
  37. h.Set("Content-Type", mtype)
  38. }
  39. if isGzipped {
  40. h.Set("Content-Encoding", "gzip")
  41. }
  42. file_writer, err := body_writer.CreatePart(h)
  43. if err != nil {
  44. glog.V(0).Infoln("error creating form file", err)
  45. return nil, err
  46. }
  47. if err = fillBufferFunction(file_writer); err != nil {
  48. glog.V(0).Infoln("error copying data", err)
  49. return nil, err
  50. }
  51. content_type := body_writer.FormDataContentType()
  52. if err = body_writer.Close(); err != nil {
  53. glog.V(0).Infoln("error closing body", err)
  54. return nil, err
  55. }
  56. resp, err := http.Post(uploadUrl, content_type, body_buf)
  57. if err != nil {
  58. glog.V(0).Infoln("failing to upload to", uploadUrl)
  59. return nil, err
  60. }
  61. defer resp.Body.Close()
  62. resp_body, err := ioutil.ReadAll(resp.Body)
  63. if err != nil {
  64. return nil, err
  65. }
  66. var ret UploadResult
  67. err = json.Unmarshal(resp_body, &ret)
  68. if err != nil {
  69. glog.V(0).Infoln("failing to read upload resonse", uploadUrl, string(resp_body))
  70. return nil, err
  71. }
  72. if ret.Error != "" {
  73. return nil, errors.New(ret.Error)
  74. }
  75. return &ret, nil
  76. }