作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想检查Azure Blob存储的容器中是否存在该文件。如果该文件存在,则我下载该文件。
最佳答案
由于没有任何 REST API 或 SDK API 来检查 Blob 是否存在,因此您无法直接检查它。据我所知,检查 blob 是否存在的唯一方法是检查获取 blob 时的错误信息。请引用Common REST API Error Codes
,如下。
以下是我使用 Microsoft Azure Storage SDK v10 for Java 检查 blob 是否存在的步骤和示例代码.
maven dependency适用于 Java 的 Azure 存储 SDK v10 如下。
<!-- 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>
生成带有 SAS 签名的 Blob URL。
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);
}
对带有 SAS 签名的 URL 发出 HTTP 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 时通过捕获相关异常来直接检查是否存在。
关于java - 如何用java检查文件是否存在于Azure Blob容器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54401827/
我是一名优秀的程序员,十分优秀!