云服务器内容精选

  • 代码示例 本示例用于将本地localfile文件上传到examplebucket桶中的example/objectname对象。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package main import ( "fmt" "os" obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs" ) func main() { //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。 //您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html。 ak := os.Getenv("AccessKeyID") sk := os.Getenv("SecretAccessKey") // 【可选】如果使用临时AK/SK和SecurityToken访问OBS,同样建议您尽量避免使用硬编码,以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。 securityToken := os.Getenv("SecurityToken") // endpoint填写Bucket对应的Endpoint, 这里以华北-北京四为例,其他地区请按实际情况填写。 endPoint := "https://obs.cn-north-4.myhuaweicloud.com" // 创建obsClient实例 // 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过obs.WithSecurityToken方法指定securityToken值。 obsClient, err := obs.New(ak, sk, endPoint, obs.WithSecurityToken(securityToken)) if err != nil { fmt.Printf("Create obsClient error, errMsg: %s", err.Error()) } input := &obs.PutFileInput{} // 指定存储桶名称 input.Bucket = "examplebucket" // 指定上传对象,此处以 example/objectname 为例。 input.Key = "example/objectname" // 指定本地文件,此处以localfile为例 input.SourceFile = "localfile" // 文件上传 output, err := obsClient.PutFile(input) if err == nil { fmt.Printf("Put file(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket) fmt.Printf("StorageClass:%s, ETag:%s\n", output.StorageClass, output.ETag) return } fmt.Printf("Put file(%s) under the bucket(%s) fail!\n", input.Key, input.Bucket) if obsError, ok := err.(obs.ObsError); ok { fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.") fmt.Println(obsError.Error()) } else { fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.") fmt.Println(err) } }
  • 接口约束 您必须是桶拥有者或拥有上传对象的权限,才能上传对象。建议使用 IAM 或桶策略进行授权,如果使用IAM则需授予obs:object:PutObject权限,如果使用桶策略则需授予PutObject权限。相关授权方式介绍可参见OBS权限控制概述,配置方式详见使用IAM自定义策略、配置对象策略。 OBS支持的Region与Endpoint的对应关系,详细信息请参见地区与终端节点。 单次上传对象大小范围是[0, 5GB]。 如果需要上传超过5GB的大文件,需要通过多段操作来分段上传。