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.

90 lines
2.2 KiB

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