🔥
Caster 開發日誌
  • Java
    • JVM Performance Tool
      • Java Debug Wire Protocol (JDWP) 的詳細介紹
      • JConsole 詳細介紹
    • Spring Boot
      • Spring Security
      • Spring Boot Admin
      • Spring Event
      • Spring AOP
      • Spring Boot JUnit 5
      • Apache Dubbo
    • Reflect 應用
    • ELK + F 建構
    • Socket.IO
    • OCR - 光學字元辨識
    • 讀取JAR resource文件
    • LocalTime & MySQL時間精度
    • Gradle multi module
    • MyBatis-Plus
    • Java Date operation
    • Java IP to Long
    • Apache Commons lang3 應用
      • Function 應用
    • Cloud Platform
      • Amazon S3
        • SDK V1
          • Bucket
        • SDK V2
          • Bucket
      • Google Cloud Platform
      • Azure Cloud
        • Storage
      • OVHcloud
        • Config
    • SSL/TLS工具
    • Util 工具
      • Jackson Json工具
      • Charles應用
      • JMeter – Performing Distributed Load Testing with Docker
    • Redis
      • Stream
      • Redisson 分布式鎖機制
      • Create Redis Cluster Using Docker
      • List Operations
    • Java 8
      • method & constructor Reference
      • CompletableFuture
      • FunctionInterface
      • Stream 應用
      • 繁簡轉換 - 簡易調整
    • MySQL
      • 建立測試用 流水號Table
      • SQL 效能調校 - Explain
      • SQL 效能調校 - Partition
      • 排程 - Event
    • Apache ShardingSphere
  • Kubernetes
    • 初入江湖(K8S)
    • 零中斷服務滾動更新
    • Kubernetes DNS
    • Ingress & Ingress Controller 教學
    • Ingress TLS Easy setup
  • 指令集
  • Telegram
  • SourceTree
    • 踩坑紀錄(ㄧ) - Git Flow
    • 踩坑紀錄(二) - 修改檔名
  • 專案統計
    • Robot
    • Recharge
  • GitHub
    • Actions
  • GitLab
    • 介紹 GitLab
    • 使用 Docker 自架 GitLab
    • 簡介 GitLab CI/CD
      • GitLab Runner 詳細介紹與設定方式
Powered by GitBook
On this page
  • 簡單說明及自身經驗
  • Service & Config
  1. Java
  2. Cloud Platform
  3. Azure Cloud

Storage

上傳物件

PreviousAzure CloudNextOVHcloud

Last updated 2 years ago

簡單說明及自身經驗

參考文件:

相較於GCP & Amazon S3 設定上簡單許多,僅需要設定好 connectString 就可以直接使用。

上傳物件

// 使用 Azure storage
// https://mvnrepository.com/artifact/com.microsoft.azure/azure-storage
implementation group: 'com.microsoft.azure', name: 'azure-storage', version: '8.6.6'

Service & Config

透過 storageConnectionString 進行身份驗證

public class AzureS3Client {

	@Value("${azure.connect.string}")
	private String storageConnectionString;
	final String containerName = "samplecontainer";

	private CloudBlobClient cloudBlobClient;
	private CloudBlobContainer cloudBlobContainer;

	@PostConstruct
	private void initializeAwsClient() {
		// Use the CloudStorageAccount object to connect to your storage account
		try {
			CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
			cloudBlobClient = storageAccount.createCloudBlobClient();
			cloudBlobContainer = cloudBlobClient.getContainerReference(containerName);
			if (cloudBlobContainer.createIfNotExists())
				log.debug(containerName + " created");
			else
				log.debug(containerName + " already exists");

		} catch (InvalidKeyException | URISyntaxException | StorageException ex) {
			// Handle the exception
			ex.printStackTrace();
		}
	}

	@Deprecated
	public boolean isDirectory(String directoryName) {
		try {
			CloudBlobDirectory blockBlobDir = cloudBlobContainer.getDirectoryReference(directoryName);
			// Blob Directories don't exists unless they have something underneath
			return blockBlobDir.listBlobs().iterator().hasNext();

		} catch (Exception e) {
//			logger.debug("isDirectory failed to lookup URI - [{}]", getUri(), e);
			e.printStackTrace();
		}
		return false;
	}

	public boolean checkBlobFolderExists(String folderName) throws StorageException, IOException, URISyntaxException {
		log.debug("checkBlobFolderExists ==>" + folderName);
		for (ListBlobItem blob : cloudBlobContainer.getDirectoryReference("文件專區").listBlobs()) {
			String blobName = blob.getUri().getPath().split("/")[3];
			if (blobName.equals(folderName))
				return true;
		}
		return false;
	}

	public boolean checkBlobFileExists(String folderName, String fileName) throws StorageException, IOException, URISyntaxException {
		log.debug("checkFolderExists ==>文件專區/" + folderName + "/附加檔案/" + fileName);
		for (ListBlobItem blob : cloudBlobContainer.getDirectoryReference("文件專區").getDirectoryReference(folderName).getDirectoryReference("附加檔案").listBlobs()) {
			int end = blob.getUri().getPath().indexOf("/附加檔案/") + "/附加檔案/".length();
			String blobName = blob.getUri().getPath().substring(end);
			if (blobName.equals(fileName))
				return true;
		}
		return false;
	}

	public String copyBlob(String sourceBlobStr, String targetBlobStr) throws StorageException, IOException, URISyntaxException {
		CloudAppendBlob sourceBlob = cloudBlobContainer.getAppendBlobReference(sourceBlobStr);
		CloudAppendBlob targetBlob = cloudBlobContainer.getAppendBlobReference(targetBlobStr);
		targetBlob.startCopy(sourceBlob);
		return targetBlob.getUri().toString();
	}

	public void uploadBlob(String localPathFileName, String fullPathFileName) throws StorageException, IOException, URISyntaxException {
		byte[] bytes = getByteArrayFromFile(localPathFileName);
		uploadBlob(bytes, fullPathFileName);
	}

	public String uploadBlob(byte[] bytes, String fullPathFileName) throws URISyntaxException, StorageException, IOException {
		log.debug("uploadBlob ->" + fullPathFileName);
		CloudAppendBlob cloudAppendBlob = cloudBlobContainer.getAppendBlobReference(fullPathFileName);
		cloudAppendBlob.uploadFromByteArray(bytes, 0, bytes.length);
		return cloudAppendBlob.getUri().toString();
	}

	public void deleteBlobFolder(String folderName) throws URISyntaxException, StorageException, IOException {

		cloudBlobContainer.getDirectoryReference("文件專區")
				.listBlobs(null, true, EnumSet.noneOf(BlobListingDetails.class), null, null).forEach(blob -> {
			if ((blob instanceof CloudBlob)) {
				String uriStr = blob.getUri().toString();
				if (uriStr.indexOf(folderName) != -1) {
					try {
						((CloudBlob) blob).deleteIfExists();
					} catch (StorageException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	public boolean deleteBlobFile(String fullFilePathName) throws URISyntaxException, StorageException, IOException {
		log.debug("deleteBlobFile ->" + fullFilePathName);
		return cloudBlobContainer.getAppendBlobReference(fullFilePathName).deleteIfExists();
	}

	private static byte[] getByteArrayFromFile(String filePath) {
		FileInputStream fileInputStream = null;
		byte[] bytesArray = null;
		FileImageInputStream fileImageInputStream = null;
		try {

			File file = new File(filePath);
			bytesArray = new byte[(int) file.length()];
			//fileInputStream = new FileInputStream(file);
			//fileInputStream.read(bytesArray);
			fileImageInputStream = new FileImageInputStream(file);
			fileImageInputStream.read(bytesArray);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fileImageInputStream != null) {
				try {
//                    fileInputStream.close();
					fileImageInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return bytesArray;
	}
}

官方文件