> For the complete documentation index, see [llms.txt](https://xu-min-chang.gitbook.io/caster-develop-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://xu-min-chang.gitbook.io/caster-develop-note/java/cloud-platform/azure-cloud/storage.md).

# Storage

上傳物件

### 簡單說明及自身經驗&#x20;

參考文件： [官方文件](https://docs.microsoft.com/zh-tw/azure/storage/files/storage-how-to-create-file-share?tabs=azure-portal)

相較於`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` 進行身份驗證

```java
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;
	}
}
```
