You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Go语言删除Azure Blob Storage中的文件

Go语言删除Azure Blob Storage单个Blob示例

前置依赖

首先安装官方Azure Blob Storage Go SDK:
go get github.com/Azure/azure-sdk-for-go/sdk/storage/azblob

完整代码示例

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)

func main() {
	// 存储账户连接字符串,可从Azure门户存储账户的访问密钥页获取
	connectionString := "<你的存储账户连接字符串>"
	// 目标容器名称
	containerName := "<目标容器名>"
	// 要删除的Blob名称(包含虚拟路径的完整路径,比如doc/report.pdf)
	blobName := "<要删除的Blob完整路径>"

	// 初始化Blob服务客户端
	client, err := azblob.NewClientFromConnectionString(connectionString, nil)
	if err != nil {
		log.Fatalf("初始化客户端失败: %v", err)
	}

	// 调用删除方法删除指定Blob
	_, err = client.DeleteBlob(context.TODO(), containerName, blobName, nil)
	if err != nil {
		log.Fatalf("删除Blob失败: %v", err)
	}

	fmt.Printf("Blob %s 删除成功\n", blobName)
}

常见使用说明

  • 存储账户连接字符串可从Azure门户存储账户的「访问密钥」页面获取
  • 如果你的存储账户开启了Blob软删除功能,需要永久删除的话,可给DeleteBlob方法传入配置参数:
    // 永久删除已开启软删除的Blob
    deleteOpts := azblob.DeleteBlobOptions{
        DeleteSnapshots: azblob.DeleteSnapshotsOptionTypeInclude.ToPtr(),
        PermanentDelete: to.Ptr(true),
    }
    _, err = client.DeleteBlob(context.TODO(), containerName, blobName, &deleteOpts)
    
  • 删除前可先调用client.NewBlobClient(containerName, blobName).Exists()方法判断目标Blob是否存在,避免抛出不必要的错误
  • 生产环境推荐使用Azure AD身份认证替代连接字符串,可通过azblob.NewClient()方法结合DefaultAzureCredential实现

内容的提问来源于stack exchange,提问作者Minathe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:45:04