Azure Storage Blob Go SDK示例
简介
前面一篇博客介绍了关于Azure ManagerAPI Go SDK的使用,本篇继续介绍使用Blob Go SDK 操作中国区Azure Blob。
SDK下载:
go get github.com/Azure/azure-storage-blob-go/2016-05-31/azblob
示例程序:
package main
import (
"bufio"
"bytes"
"context"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/url"
"os"
"strconv"
"time"
"github.com/Azure/azure-storage-blob-go/2016-05-31/azblob"
)
func randomString() string {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return strconv.Itoa(r.Int())
}
func handleErrors(err error) {
if err != nil {
if serr, ok := err.(azblob.StorageError); ok { // This error is a Service-specific
switch serr.ServiceCode() { // Compare serviceCode to ServiceCodeXxx constants
case azblob.ServiceCodeContainerAlreadyExists:
fmt.Println("Received 409. Container already exists")
return
}
}
log.Fatal(err)
}
}
func main() {
fmt.Printf("Azure Blob storage quick start sample\n")
var accountName string = "<storage account name>"
var accountKey string = "<storage account key>"
if len(accountName) == 0 || len(accountKey) == 0 {
log.Fatal("Either the AZURE_STORAGE_ACCOUNT or AZURE_STORAGE_ACCESS_KEY environment variable is not set")
}
// Create a default request pipeline using your storage account name and account key.
credential := azblob.NewSharedKeyCredential(accountName, accountKey)
p := azblob.NewPipeline(credential, azblob.PipelineOptions{})
// Create a random string for the quick start container
containerName := fmt.Sprintf("quickstart-%s", randomString())
// From the Azure portal, get your storage account blob service URL endpoint.
URL, _ := url.Parse(
fmt.Sprintf("https://%s.blob.core.chinacloudapi.cn/%s", accountName, containerName))
// Create a ContainerURL object that wraps the container URL and a request
// pipeline to make requests.
containerURL := azblob.NewContainerURL(*URL, p)
// Create the container
fmt.Printf("Creating a container named %s\n", containerName)
ctx := context.Background() // This example uses a never-expiring context
_, err := containerURL.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
handleErrors(err)
// Create a file to test the upload and download.
fmt.Printf("Creating a dummy file to test the upload and download\n")
data := []byte("hello world\nthis is a blob\n")
fileName := randomString()
err = ioutil.WriteFile(fileName, data, 0700)
handleErrors(err)
// Here's how to upload a blob.
blobURL := containerURL.NewBlockBlobURL(fileName)
file, err := os.Open(fileName)
handleErrors(err)
// You can use the low-level PutBlob API to upload files. Low-level APIs are simple wrappers for the Azure Storage REST APIs.
// Note that PutBlob can upload up to 256MB data in one shot. Details: https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob
// Following is commented out intentionally because we will instead use UploadFileToBlockBlob API to upload the blob
// _, err = blobURL.PutBlob(ctx, file, azblob.BlobHTTPHeaders{}, azblob.Metadata{}, azblob.BlobAccessConditions{})
// handleErrors(err)
// The high-level API UploadFileToBlockBlob function uploads blocks in parallel for optimal performance, and can handle large files as well.
// This function calls PutBlock/PutBlockList for files larger 256 MBs, and calls PutBlob for any file smaller
fmt.Printf("Uploading the file with blob name: %s\n", fileName)
_, err = azblob.UploadFileToBlockBlob(ctx, file, blobURL, azblob.UploadToBlockBlobOptions{
BlockSize: 4 * 1024 * 1024,
Parallelism: 16})
handleErrors(err)
// List the blobs in the container
for marker := (azblob.Marker{}); marker.NotDone(); {
// Get a result segment starting with the blob indicated by the current Marker.
listBlob, err := containerURL.ListBlobs(ctx, marker, azblob.ListBlobsOptions{})
handleErrors(err)
// ListBlobs returns the start of the next segment; you MUST use this to get
// the next segment (after processing the current result segment).
marker = listBlob.NextMarker
// Process the blobs returned in this result segment (if the segment is empty, the loop body won't execute)
for _, blobInfo := range listBlob.Blobs.Blob {
fmt.Print("Blob name: " + blobInfo.Name + "\n")
}
}
// Here's how to download the blob. NOTE: This method automatically retries if the connection fails
// during download (the low-level GetBlob function does NOT retry errors when reading from its stream).
stream := azblob.NewDownloadStream(ctx, blobURL.GetBlob, azblob.DownloadStreamOptions{})
downloadedData := &bytes.Buffer{}
_, err = downloadedData.ReadFrom(stream)
handleErrors(err)
// The downloaded blob data is in downloadData's buffer. :Let's print it
fmt.Printf("Downloaded the blob: " + downloadedData.String())
// Cleaning up the quick start by deleting the container and the file created locally
fmt.Printf("Press enter key to delete the sample files, example container, and exit the application.\n")
bufio.NewReader(os.Stdin).ReadBytes('\n')
fmt.Printf("Cleaning up.\n")
containerURL.Delete(ctx, azblob.ContainerAccessConditions{})
file.Close()
os.Remove(fileName)
}
测试结果:
Azure Blob storage quick start sample
Creating a container named quickstart-6677502160360014613
Creating a dummy file to test the upload and download
Uploading the file with blob name: 186632235901289029
Blob name: 186632235901289029
Downloaded the blob: hello world
this is a blob
Press enter key to delete the sample files, example container, and exit the application.
Cleaning up.
参考链接:
Azure Storage Blob Go SDK示例的更多相关文章
- Connect China Azure Storage Blob By Container Token In Python SDK
简介: 基于Python SDK,使用Container Token操作container对象.关于Token的生成可以使用Storage SDK创建,也可以使用工具快速创建供测试. 示例代码: fr ...
- 关于Azure Storage Blob Content-Disposition 使用学习
概述 在常规的HTTP应答中,Content-Disposition 消息头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地.通俗的解释就是对 ...
- 【Azure 存储服务】代码版 Azure Storage Blob 生成 SAS (Shared Access Signature: 共享访问签名)
问题描述 在使用Azure存储服务,为了有效的保护Storage的Access Keys.可以使用另一种授权方式访问资源(Shared Access Signature: 共享访问签名), 它的好处可 ...
- Azure系列2.1 —— com.microsoft.azure.storage.blob
网上azure的资料较少,尤其是API,全是英文的,中文资料更是少之又少.这次由于公司项目需要使用Azure,所以对Azure的一些学习心得做下笔记,文中不正确地方请大家指正. Azure Blob ...
- Azure Storage Blob文件重命名
Azure Storage的SDK并没有提供文件重命名的方法,而且从StorageExplorer管理工具里操作修改文件名的时候也有明确提示: 是通过复制当前文件并命名为新文件名再删除旧文件,不保存快 ...
- Azure Storage Blob文件名区分大小写
最近在使用Azure Storage的时候发现Storage的命名是区分大小写的,导致我们系统在更新图片的时候有时候更新不上,最终通过判断处理文件名解决. 因此我们在使用Storage需要注意一下文件 ...
- 如何获取Azure Storage Blob的MD5值
问题表述 直接使用CloudBlockBlob对象获取的Properties是空的,无法获取到对象的MD5值,后台并未进行属性值的填充 前提:blob属性本省包含md5值,某些方式上传的blob默认并 ...
- Azure Storage Blob 属性设置
概述 在使用SDK做Blob对象属性的获取或设置时,如果只是直接使用get或set方法,是无法成功获取或设置blob对象的属性.主要是因为在获取对象时,对象的属性默认并未被填充到对象,这就需要执行额外 ...
- 【Azure Developer】使用 Python SDK连接Azure Storage Account, 计算Blob大小代码示例
问题描述 在微软云环境中,使用python SDK连接存储账号(Storage Account)需要计算Blob大小?虽然Azure提供了一个专用工具Azure Storage Explorer可以统 ...
随机推荐
- STL模板整理 pair
pair pair是一种模板类型,其中包含两个数据值,两个数据的类型可以不同.如果一个函数有两个返回值的话,如果是相同类型,就可以用数组返回,如果是不同类型,就可以自己写个struct ,但为了方便就 ...
- Mathematica作图
第2讲 在Mathematica中作图 一个较强的符号计算系统均有很好的绘图功能,Mathematica也不例外,Mathematica 拥有非常强大的绘图功能.并且提供了一大批基本数学函数的图 ...
- 蒟蒻的9个背包的浩大工程(更新中)(无限延期)(太长了不舍删虽然写的lj的一匹)
所以说这就是一篇写炸的废文!!!! 所以说背包直接看dd大神的就好了,算了瞎写写吧. 0/1背包 有n件物品和一个容量为C的背包.第i件物品的重量是w[i],价值是v[i].求解将哪些物品放入背包可使 ...
- 洛谷——P2128 赤壁之战
P2128 赤壁之战 题目描述 赤壁之战,黄盖率舰满载薪草膏油诈降曹军. 受庞统所授的连环计,曹军战船之间由铁索相连,没有两艘战船在同一位置,也没有铁索两两相交或穿过战船.每艘船都有其一定的战略价值. ...
- 显示(explicit )与隐式(implicit)转换操作符
class Program { static void Main(string[] args) { /* * 不管是显示还是隐式转换,一种类型都只能出现一次 */ Console.WriteLine( ...
- wildfly8.1部署注意事项
wildfly8.1部署注意事项 jboss 最近新项目上线,本人部署过程中总结了以下几点比较关键的地方,看是否对大家有用处 服务器改成支持外网访问 在standalone.xml文件中找到 ...
- Redis核心解读
http://www.wzxue.com/redis核心解读/
- 【POI】对于POI无法处理超大xls等文件,官方解决方法【已解决】【多线程提升速率待定】
本次使用POI处理xlsx文件,莫名的遇到了一个无法逾越的问题. 总共71个xlsx文件,单个文件最大达到50M以上,71个xls文件摆在那里就有3-4G的大小. 在起始处理的时候,发现原本适用于正常 ...
- oracle解决连接池不足
select count(*) from v$process;----系统有多少连接数 select value from v$parameter where name = 'processe ...
- Windows 2008 R2
1简介 Windows 2008 R2是微软针对windows 7所推出的Windows server操作系统.为了使企业减少操作成本和提高效率,Windows Server 2008 R2对企业资源 ...