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.

91 lines
2.3 KiB

  1. package operation
  2. import (
  3. "code.google.com/p/weed-fs/go/glog"
  4. "io"
  5. "mime"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. )
  12. type SubmitResult struct {
  13. FileName string `json:"fileName"`
  14. FileUrl string `json:"fileUrl"`
  15. Fid string `json:"fid"`
  16. Size int `json:"size"`
  17. Error string `json:"error"`
  18. }
  19. func Submit(master string, reader io.Reader, replication string) (result SubmitResult, err error) {
  20. assignResult, assignError := Assign(master, 1, replication)
  21. if assignError != nil {
  22. result.Error = assignError.Error()
  23. return
  24. }
  25. url := "http://" + assignResult.PublicUrl + "/" + assignResult.Fid
  26. uploadResult, uploadError := Upload(url, "", reader, false, "")
  27. if uploadError != nil {
  28. result.Error = uploadError.Error()
  29. return
  30. }
  31. result.Size = uploadResult.Size
  32. result.FileUrl = url
  33. result.Fid = assignResult.Fid
  34. return result, nil
  35. }
  36. func SubmitFiles(master string, files []string, replication string) ([]SubmitResult, error) {
  37. results := make([]SubmitResult, len(files))
  38. for index, file := range files {
  39. results[index].FileName = file
  40. }
  41. ret, err := Assign(master, len(files), replication)
  42. if err != nil {
  43. for index, _ := range files {
  44. results[index].Error = err.Error()
  45. }
  46. return results, err
  47. }
  48. for index, file := range files {
  49. fid := ret.Fid
  50. if index > 0 {
  51. fid = fid + "_" + strconv.Itoa(index)
  52. }
  53. results[index].Size, err = upload(file, ret.PublicUrl, fid)
  54. if err != nil {
  55. fid = ""
  56. results[index].Error = err.Error()
  57. }
  58. results[index].Fid = fid
  59. results[index].FileUrl = ret.PublicUrl + "/" + fid
  60. }
  61. return results, nil
  62. }
  63. func upload(filename string, server string, fid string) (int, error) {
  64. glog.V(2).Info("Start uploading file:", filename)
  65. fh, err := os.Open(filename)
  66. if err != nil {
  67. glog.V(0).Info("Failed to open file: ", filename)
  68. return 0, err
  69. }
  70. fi, fiErr := fh.Stat()
  71. if fiErr != nil {
  72. glog.V(0).Info("Failed to stat file:", filename)
  73. return 0, fiErr
  74. }
  75. filename = path.Base(filename)
  76. isGzipped := path.Ext(filename) == ".gz"
  77. if isGzipped {
  78. filename = filename[0 : len(filename)-3]
  79. }
  80. mtype := mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  81. ret, e := Upload("http://"+server+"/"+fid+"?ts="+strconv.Itoa(int(fi.ModTime().Unix())), filename, fh, isGzipped, mtype)
  82. if e != nil {
  83. return 0, e
  84. }
  85. return ret.Size, e
  86. }