【发布时间】:2019-01-01 23:11:18
【问题描述】:
我的任务是使用 Azure Blob 存储从应用程序下载简单的 .txt 文件。该代码应该可以工作。这不是我写的,但它看起来不错localhost,但不在公开网站上。
这些是我做的步骤:
我在某处看到它可能是由不允许应用访问存储的 Azure CORS 设置引起的。这是我到目前为止所做的:
- 访问了 portal.azure.com 并更改了 CORS 设置,如下所示:
- 在此 Microsoft 链接下发现了一些关于将一些代码放入应用程序的信息,但它不是 Java。我猜Java中有一些类比的方法: https://blogs.msdn.microsoft.com/windowsazurestorage/2014/02/03/windows-azure-storage-introducing-cors/ 。在 Azure 门户中添加 CORS 规则后是否需要?
另外,我发现它可能是由存储访问权限引起的。公共访问级别设置为容器:
我收到的BlobNotFound 错误还有什么问题?希望我在这里提供了足够的信息,但如果需要更多信息,请在评论中说,我会提供。
这是应该下载此方法附件的代码,包含在 3 个类中:
控制器类部分:
@GetMapping("/download/{id}")
@ResponseStatus(HttpStatus.OK)
public void downloadAttachment(@PathVariable long id, HttpServletResponse response) throws IOException {
dataUploadRequestAttachmentService.downloadStaticAttachment(response, id);
}
控制器服务类部分:
public void downloadStaticAttachment(HttpServletResponse response, long id) throws IOException {
ArticleAttachment articleAttachment = this.findAttachment(id);
String mimeType = URLConnection.guessContentTypeFromName(articleAttachment.getName());
if (mimeType == null){
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", articleAttachment.getName()));
azureBlobStorageArticleAttachmentService.downloadArticleAttachment(
articleAttachment.getName(),
articleAttachment.getId(),
response.getOutputStream()
);
}
还有 AzureBlobStorageArticleAttachmentService 类:
public void downloadArticleAttachment(String attachmentName, Long articleId, OutputStream outputStream) {
try {
CloudBlockBlob blob = container.getBlockBlobReference(String.format("%s_%s", articleId, attachmentName));
blob.download(outputStream);
} catch (URISyntaxException | StorageException e) {
e.printStackTrace();
log.error(String.format("Download article attachment %s error", attachmentName));
}
}
【问题讨论】:
-
您能否展示一些有关如何下载 blob 的代码?
-
当然。我已经编辑了帖子并将代码添加到问题的末尾部分
标签: java azure spring-boot azure-blob-storage