我想检查该文件是否存在于Azure Blob存储的容器中。如果该文件存在,那么我下载该文件。
由于没有任何REST API或SDK API来检查blob是否存在,因此您无法直接检查它。据我所知,检查blob存在的唯一方法是在获取blob时检查错误信息,请参考Common REST API Error Codes
,如下所示。
这是我使用Microsoft Azure Storage SDK v10 for Java检查blob是否存在的步骤和示例代码。
Azure Storage SDK v10 for Java的maven dependency如下所示。
<!-- https://mvnrepository.com/artifact/com.microsoft.azure/azure-storage-blob -->
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage-blob</artifactId>
<version>10.4.0</version>
</dependency>
String accountName = "<your storage account name>";
String accountKey = "<your storage account key>";
public String generateUrlWithSAS(String containerName, String blobName) throws InvalidKeyException {
SharedKeyCredentials credentials = new SharedKeyCredentials(accountName, accountKey);
ServiceSASSignatureValues values = new ServiceSASSignatureValues()
.withProtocol(SASProtocol.HTTPS_ONLY) // Users MUST use HTTPS (not HTTP).
.withExpiryTime(OffsetDateTime.now().plusDays(2)) // 2 days before expiration.
.withContainerName(containerName)
.withBlobName(blobName);
BlobSASPermission permission = new BlobSASPermission()
.withRead(true)
.withAdd(true)
.withWrite(true);
values.withPermissions(permission.toString());
SASQueryParameters serviceParams = values.generateSASQueryParameters(credentials);
String sasSign = serviceParams.encode();
return String.format(Locale.ROOT, "https://%s.blob.core.windows.net/%s/%s%s", accountName, containerName, blobName, sasSign);
}
Head
请求以检查响应状态代码
public static boolean exists(String urlWithSAS) throws MalformedURLException, IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(urlWithSAS).openConnection();
conn.setRequestMethod("HEAD");
return conn.getResponseCode() == 200;
}
此外,您可以通过在下载blob时捕获相关异常来直接检查存在。
如果你是blob的拥有者,那么更简单的方式(并且不会让我感到困惑)受到@Peter Pan的回答的启发。
boolean blobExists(String containerName, String blobName) {
ServiceURL serviceUrl = getServiceUrl();
HttpURLConnection httpUrlConnection = (HttpURLConnection)
serviceUrl.createContainerURL(containerName)
.createBlockBlobURL(blobName)
.toURL().openConnection();
httpUrlConnection.setRequestMethod("HEAD");
return httpUrlConnection.getResponseCode() / 100 == 2;
}
ServiceURL getServiceUrl() {
SharedKeyCredentials credentials = new SharedKeyCredentials(accountName, accountKey);
return new ServiceURL(new URL(azureUrl), StorageURL.createPipeline(credentials, new PipelineOptions()));
}
用库com.microsoft.azure:azure-storage-blob:10.5.0
测试。