func upload(filepath string) { //初始化AK,SK conf.ACCESS_KEY = "JRxl723OpszbaeNZZ9kdvlqcylRF18a8gLSTmOie" conf.SECRET_KEY = "H5IbPfFgJWCdzOTnl1YMuhP1rVycAJgDnGD-3cyl" //创建一个Client c := kodo.New(0, nil) //设置上传的策略 policy := &kodo.PutPolicy{ Scope: bucket, //设置Token过期时间 Expires: 3600, } //生成一个上传token token := c.MakeUptoken(policy) //构建一个uploader zone := 0 uploader := kodocli.NewUploader(zone, nil) var ret PutRet //设置上传文件的路径 // filepath := "/home/xinglong/blog" //调用PutFileWithoutKey方式上传,没有设置saveasKey以文件的hash命名 res := uploader.PutFileWithoutKey(nil, &ret, token, filepath, nil) //打印返回的信息 fmt.Println(ret) //打印出错信息 if res != nil { fmt.Println("io.Put failed:", res) return } }
// upload image func (this *ImageRespository) UploadImage(imgPath string) (bool, error) { zone := 0 uploader := kodocli.NewUploader(zone, nil) ctx := context.Background() err := uploader.PutFile(ctx, nil, this.GetUPToken(), "", imgPath, nil) if err != nil { return false, err } return true, nil }
func main() { var key string flag.StringVar(&key, "k", "", "The key of upload file") flag.Parse() filename := flag.Arg(0) if filename == "" { usage() return } fileAbsPath, _ := filepath.Abs(filename) if _, err := os.Stat(fileAbsPath); os.IsNotExist(err) { fmt.Println("No such file to upload: ", filename) return } if key == "" { key = filepath.Base(fileAbsPath) } fmt.Println("Upload file with key: ", key) resp, err := http.Get(UPTOKEN_URL + "?key=" + key) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } var uptoken Uptoken json.Unmarshal(body, &uptoken) zone := 0 uploader := kodocli.NewUploader(zone, nil) ctx := context.Background() err = uploader.PutFile(ctx, nil, uptoken.Value, key, fileAbsPath, nil) if err != nil { fmt.Println(err) return } fmt.Println("Upload file success, You can download it from:") fmt.Println(kodocli.MakeBaseUrl(DOMAIN, key)) }