upload.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package main
  2. import (
  3. "fmt"
  4. "flag"
  5. "github.com/satori/go.uuid"
  6. "io/ioutil"
  7. "bytes"
  8. "mime/multipart"
  9. "net/http"
  10. "github.com/tidwall/gjson"
  11. "github.com/qiniu/api.v7/storage"
  12. "github.com/qiniu/api.v7/auth"
  13. "path"
  14. "os"
  15. "time"
  16. )
  17. var (
  18. accessKey = "7msMIyQ9xOjOwqO9JSPl"
  19. secretKey = "JU8kLByQ1U1Zgkfni95IC9ttvfv5NLC3qO642R1Z"
  20. bucket = "makeup-magic"
  21. )
  22. type returnBody struct {
  23. key string
  24. hash string
  25. fsize int
  26. bucket string
  27. url string
  28. }
  29. func main() {
  30. file := flag.String("f", "test.zip", "本地文件名")
  31. flag.Parse()
  32. //file_type := path.Base(*file)
  33. file_type := path.Ext(*file)
  34. if !PathExists(*file) {
  35. nt := time.Now().Format("2006-01-02 15:04:05")
  36. fmt.Printf("[%s]文件不存在! %s\n", nt, *file)
  37. return
  38. }
  39. u1, _ := uuid.NewV4()
  40. key := u1.String() + file_type
  41. putPolicy := storage.PutPolicy{
  42. Scope: bucket + ":" + key,
  43. ReturnBody: `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"url":"https://makeup-magic.zone1.meitudata.com/` + key + `"}`,
  44. }
  45. mac := auth.New(accessKey, secretKey)
  46. upToken := putPolicy.UploadToken(mac)
  47. file_data, _ := ioutil.ReadFile(*file)
  48. body := new(bytes.Buffer)
  49. w := multipart.NewWriter(body)
  50. content_type := w.FormDataContentType()
  51. //form
  52. w.WriteField("token", upToken)
  53. w.WriteField("key", key)
  54. file1, _ := w.CreateFormFile("file", key)
  55. file1.Write(file_data)
  56. w.Close()
  57. //request
  58. req, _ := http.NewRequest("POST", "https://up.meitudata.com", body)
  59. req.Header.Set("Content-Type", content_type)
  60. resp, _ := http.DefaultClient.Do(req)
  61. data, _ := ioutil.ReadAll(resp.Body)
  62. resp.Body.Close()
  63. jsonStr := string(data)
  64. url := gjson.Get(jsonStr, "url")
  65. fmt.Println(url)
  66. }
  67. func PathExists(path string) bool {
  68. _, err := os.Stat(path)
  69. if err == nil {
  70. return true
  71. }
  72. if os.IsNotExist(err) {
  73. return false
  74. }
  75. return false
  76. }