1.下載七牛擴展庫git
go get github.com/qiniu/api.v7
2.導入擴展庫github
import ( "github.com/qiniu/api.v7/auth/qbox" "github.com/qiniu/api.v7/storage" )
3.完整示例代碼api
package main import ( "context" "fmt" "github.com/qiniu/api.v7/auth/qbox" "github.com/qiniu/api.v7/storage" ) var ( accessKey = "TmRBqO9olxxPJ3dNKTHJKHGGFGq-9YxOqS46vZj-AMT" // 七牛的accessKey 去七牛後臺獲取 secretKey = "HPLxrnM5wK8D7FnTYw4l-xHJGFFDDDo9wKtpr9LqmCA" // 七牛的secretKey 去七牛後臺獲取 bucket = "youliaoit" // 上傳空間 去七牛後臺建立 ) func main() { // 鑑權 mac := qbox.NewMac(accessKey, secretKey) // 上傳策略 putPolicy := storage.PutPolicy{ Scope: bucket, Expires: 7200, } // 獲取上傳token upToken := putPolicy.UploadToken(mac) // 上傳Config對象 cfg := storage.Config{} cfg.Zone = &storage.ZoneHuanan //指定上傳的區域 cfg.UseHTTPS = false // 是否使用https域名 cfg.UseCdnDomains = false //是否使用CDN上傳加速 // 七牛key qiniuKey := "qiniu/20200113/a.png" // 構建上傳的對象 base64Uploader := storage.NewBase64Uploader(&cfg) ret := storage.PutRet{} // 圖片base64格式的數據 注意 須要去掉 前面相似data:image/png;base64,的數據 data := []byte("iVBORw0KGgoAAAANSUhEUgAAAE8AAAA+CAYAAABqSkbiAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8Y/7X4brMvvM7xmf7bntD4EhFq1jmCx/4zZQJz+XWVV/Fm4PLJduhkcRyPDEhgKmKFI0DZilbx+KWxgbeCWCLV1DGGC+D8SZZII=") err := base64Uploader.Put(context.Background(), &ret, upToken, qiniuKey, data, nil) if err != nil { fmt.Println("上傳文件失敗,緣由:", err) return } fmt.Println("上傳成功,key爲:", ret.Key) }
4.附加七牛雲go的文檔地址3d