【问题标题】:Download list of blobs from Azure Blob Storage从 Azure Blob 存储下载 Blob 列表
【发布时间】:2019-12-19 03:20:47
【问题描述】:

我已经用正确的连接字符串创建了CloudBlobContainer

@Bean
@SneakyThrows
public CloudBlobContainer blobContainer(CloudStorageAccount cloudStorageAccount) {
    return cloudStorageAccount
            .createCloudBlobClient()
            .getContainerReference(containerName);
}

我看到使用 blobContainer.listBlobs() 的 blob 列表

目前,我正在寻找从特定文件夹下载列表 blob 的最有效方法。

【问题讨论】:

  • 您是要从特定文件夹下载 blob,还是只列出文件夹中的 blob?
  • @GauravMantri 我需要从容器包含的文件夹中下载每个 blob。文件夹名称将是请求的参数。

标签: java azure spring-boot azure-blob-storage


【解决方案1】:

您可以通过以下两种方式进行操作

(i) AZcopy - AzCopy /Source:https://myaccount.file.core.windows.net/demo/ /Dest:C:\myfolder /SourceKey:key /S

(ii) 通过 Azure Cli -

# Create a directory to store all the blobs
mkdir /downloaded-container && cd /downloaded-container

# Get all the blobs
BLOBS=$(az storage blob list -c $CONTAINER \
    --account-name $ACCOUNT_NAME --sas-token "$SAS_TOKEN" \
    --query [*].name --output tsv)

# Download each one
for BLOB in $BLOBS
do
  echo "********Downloading $BLOB"
  az storage blob download -n $BLOB -f $BLOB -c $CONTAINER --account-name $ACCOUNT_NAME --sas-token "$SAS_TOKEN"
done

如果您只想通过代码,这里是 sample repo,因为没有直接的方法可以通过 SDK。

HttpGet httpGet = new HttpGet(urlString);
            signRequest(httpGet, resourcePath, account, hashFunction);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                System.out.println(response.getStatusLine());

【讨论】:

    【解决方案2】:

    listBlobs() 方法有一个overload,它接受prefix 作为参数。

    public Iterable<ListBlobItem> listBlobs(final String prefix, final boolean useFlatBlobListing) {
            return this.listBlobs(prefix, useFlatBlobListing, EnumSet.noneOf(BlobListingDetails.class), null, null);
        }
    

    您需要将path of the folder 传递为prefix,并将true 传递为useFlatBlobListing,这将列出该虚拟文件夹中的所有blob。

    获得 Blob 列表后,您可以在每个 Blob 上使用 downloadToFile 方法下载 Blob。

    【讨论】:

      【解决方案3】:

      一段时间后我发现我可以将CloudBlockBlob类型应用到ListBlobItem和下载方法。

      @Bean
      @SneakyThrows
      public CommandLineRunner commandLineRunner(CloudBlobContainer blobContainer) {
          return args -> {
              Sets.newConcurrentHashSet(blobContainer.listBlobs("documents/"))
                      .stream()
                      .filter(it -> it.getUri().toString().contains("pdf"))
                      .forEach(it -> {
                          ((CloudBlockBlob) it).downloadToFile(((CloudBlockBlob) it).getName());
                      });
      
          };
      }
      

      谢谢大家。特别是@GauravMantri

      【讨论】:

        猜你喜欢
        • 2019-09-05
        • 2012-12-08
        • 2016-02-29
        • 2021-12-08
        • 2018-11-21
        • 2015-06-20
        • 2022-11-02
        相关资源
        最近更新 更多