封装微软(Microsoft) Azure 获得container 实现增加、查询、删除功能

1. 所需 jar 包:

<!--microsoft azure-->
<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-storage</artifactId>
    <version>7.0.0</version>
</dependency>

2. 代码:

package com.dmap.base.units.azure.blob;

import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;

public class AzureApp {

    private AzureApp() {
    }

    private static final Logger logger = LoggerFactory.getLogger(AzureApp.class);

    /**
     * 1步:获取要使用的容器
     *
    * @param accountName   使用 Azure 门户中列出的存储帐户的名称
     * @param acountKey     存储帐户的主访问密钥
     * @param containerName 1.容器名称必须以字母或数字开头,并且只能包含字母、数字和短划线 (-) 字符。
     *                      2.每个短划线 (-) 字符的前面和后面都必须是一个字母或数字;在容器名称中不允许连续的短划线 (-)     *                      3.容器名称中的所有字母都必须为小写。
     *                      4.容器名称必须介于 3 63 个字符。
     * @return
     */
    public static CloudBlobContainer getCloudBlobContainer(String accountName, String acountKey, String containerName) {
        //获取存储连接字符串
          String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=" + accountName + ";AccountKey=" + acountKey + ";EndpointSuffix=core.chinacloudapi.cn";
        CloudStorageAccount storageAccount;
        CloudBlobClient blobClient = null;
        CloudBlobContainer container = null;
        try {
            storageAccount = CloudStorageAccount.parse(storageConnectionString);
            blobClient = storageAccount.createCloudBlobClient();
            container = blobClient.getContainerReference(containerName);
            container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());
        } catch (URISyntaxException | InvalidKeyException | StorageException e) {
            logger.error("1步:获取要使用的容器 error from Azure server. ", e);
        } catch (Exception e) {
            logger.error("1步:获取要使用的容器 error from Azure server. ", e);
        }
        return container;
    }

    /**
     * 上传Blob
     * 创建 Blob或更新Blob(如果该 Blob 已存在)
      *
     * @param container 要上传的容器
      * @param filePath  文件路径 eg: "/home/edmond/Pictures/古天乐.jpg"
     * @return blob url eg: "https://testpmpd.blob.core.chinacloudapi.cn/pmpd-container/古天乐.jpg"
     */
    public static String uploadBlob(CloudBlobContainer container, String filePath) {
        FileInputStream fileInputStream = null;
        CloudBlockBlob blob = null;
        try {
            File source = new File(filePath);
            blob = container.getBlockBlobReference(source.getName());
            fileInputStream = new FileInputStream(source);
            blob.upload(fileInputStream, source.length());
        } catch (URISyntaxException | StorageException | FileNotFoundException e) {
            logger.error("上传Blob error from Azure server. ", e);
        } catch (IOException e) {
            logger.error("上传Blob error from Azure server. ", e);
        } catch (Exception e) {
            logger.error("上传Blob error from Azure server. ", e);
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                logger.error("上传Blob error from Azure server. ", e);
            }
        }
        String returnValue = null;
        if (blob != null) {
            returnValue = blob.getUri().toString();
        }
        return returnValue;
    }

    /**
     * 下载 Blob
     *
     * @param container 要下载的容器
      * @param filePath  下载文件要存储的文件夹路径 eg: "/home/edmond/Pictures/"
     * @param blobName  要下载的blobeg: "古天乐.jpg"
     */
    public static void downloadBlob(CloudBlobContainer container, String filePath, String blobName) {
        FileOutputStream fileOutputStream = null;
        try {
            for (ListBlobItem blobItem : container.listBlobs()) {
                if (blobItem instanceof CloudBlob) {
                    CloudBlob blob = (CloudBlob) blobItem;
                    if (blob.getName().equals(blobName)) {
                        fileOutputStream = new FileOutputStream(filePath + blob.getName());
                        blob.download(fileOutputStream);
                    }
                }
            }
        } catch (FileNotFoundException | StorageException e) {
            logger.error("下载 Blob error from Azure server. ", e);
        } catch (IOException e) {
            logger.error("下载 Blob error from Azure server. ", e);
        } catch (Exception e) {
            logger.error("下载 Blob error from Azure server. ", e);
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                logger.error("下载 Blob error from Azure server. ", e);
            }
        }
    }

    /**
     * 删除 Blob
     *
     * @param container 文件所在的容器
      * @param blobName  要删除的文件名 eg: "古天乐.jpg"
     * @return true or false
     */
    public static boolean deleteBlob(CloudBlobContainer container, String blobName) {
        boolean success = false;
        try {
            CloudBlockBlob blob = container.getBlockBlobReference(blobName);
            success = blob.deleteIfExists();
        } catch (URISyntaxException | StorageException e) {
            logger.error("删除 Blob error from Azure server. ", e);
        } catch (Exception e) {
            logger.error("删除 Blob error from Azure server. ", e);
        }
        return success;
    }

}

猜你喜欢

转载自blog.csdn.net/xinqin200612/article/details/79966594
今日推荐