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.

135 lines
3.6 KiB

12 years ago
  1. package operation
  2. import (
  3. "bytes"
  4. "compress/flate"
  5. "compress/gzip"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime"
  12. "mime/multipart"
  13. "net/http"
  14. "net/textproto"
  15. "path/filepath"
  16. "strings"
  17. "github.com/chrislusf/seaweedfs/weed/glog"
  18. "github.com/chrislusf/seaweedfs/weed/security"
  19. )
  20. type UploadResult struct {
  21. Name string `json:"name,omitempty"`
  22. Size uint32 `json:"size,omitempty"`
  23. Error string `json:"error,omitempty"`
  24. ETag string `json:"eTag,omitempty"`
  25. }
  26. var (
  27. client *http.Client
  28. )
  29. func init() {
  30. client = &http.Client{Transport: &http.Transport{
  31. MaxIdleConnsPerHost: 1024,
  32. }}
  33. }
  34. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  35. // Upload sends a POST request to a volume server to upload the content
  36. func Upload(uploadUrl string, filename string, reader io.Reader, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (*UploadResult, error) {
  37. contentIsGzipped := isGzipped
  38. shouldGzipNow := false
  39. if !isGzipped {
  40. if shouldBeZipped, iAmSure := IsGzippableFileType(filepath.Base(filename), mtype); iAmSure && shouldBeZipped {
  41. shouldGzipNow = true
  42. contentIsGzipped = true
  43. }
  44. }
  45. return upload_content(uploadUrl, func(w io.Writer) (err error) {
  46. if shouldGzipNow {
  47. gzWriter, _ := gzip.NewWriterLevel(w, flate.BestSpeed)
  48. _, err = io.Copy(gzWriter, reader)
  49. gzWriter.Close()
  50. } else {
  51. _, err = io.Copy(w, reader)
  52. }
  53. return
  54. }, filename, contentIsGzipped, mtype, pairMap, jwt)
  55. }
  56. func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error, filename string, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (*UploadResult, error) {
  57. body_buf := bytes.NewBufferString("")
  58. body_writer := multipart.NewWriter(body_buf)
  59. h := make(textproto.MIMEHeader)
  60. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  61. if mtype == "" {
  62. mtype = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  63. }
  64. if mtype != "" {
  65. h.Set("Content-Type", mtype)
  66. }
  67. if isGzipped {
  68. h.Set("Content-Encoding", "gzip")
  69. }
  70. file_writer, cp_err := body_writer.CreatePart(h)
  71. if cp_err != nil {
  72. glog.V(0).Infoln("error creating form file", cp_err.Error())
  73. return nil, cp_err
  74. }
  75. if err := fillBufferFunction(file_writer); err != nil {
  76. glog.V(0).Infoln("error copying data", err)
  77. return nil, err
  78. }
  79. content_type := body_writer.FormDataContentType()
  80. if err := body_writer.Close(); err != nil {
  81. glog.V(0).Infoln("error closing body", err)
  82. return nil, err
  83. }
  84. req, postErr := http.NewRequest("POST", uploadUrl, body_buf)
  85. if postErr != nil {
  86. glog.V(0).Infoln("failing to upload to", uploadUrl, postErr.Error())
  87. return nil, postErr
  88. }
  89. req.Header.Set("Content-Type", content_type)
  90. for k, v := range pairMap {
  91. req.Header.Set(k, v)
  92. }
  93. if jwt != "" {
  94. req.Header.Set("Authorization", "BEARER "+string(jwt))
  95. }
  96. resp, post_err := client.Do(req)
  97. if post_err != nil {
  98. glog.V(0).Infoln("failing to upload to", uploadUrl, post_err.Error())
  99. return nil, post_err
  100. }
  101. defer resp.Body.Close()
  102. etag := getEtag(resp)
  103. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  104. if ra_err != nil {
  105. return nil, ra_err
  106. }
  107. var ret UploadResult
  108. unmarshal_err := json.Unmarshal(resp_body, &ret)
  109. if unmarshal_err != nil {
  110. glog.V(0).Infoln("failing to read upload response", uploadUrl, string(resp_body))
  111. return nil, unmarshal_err
  112. }
  113. if ret.Error != "" {
  114. return nil, errors.New(ret.Error)
  115. }
  116. ret.ETag = etag
  117. return &ret, nil
  118. }
  119. func getEtag(r *http.Response) (etag string) {
  120. etag = r.Header.Get("ETag")
  121. if strings.HasPrefix(etag, "\"") && strings.HasSuffix(etag, "\"") {
  122. etag = etag[1 : len(etag)-1]
  123. }
  124. return
  125. }