【问题标题】:Set the ContentType on an Azure Blob Storage item在 Azure Blob 存储项上设置 ContentType
【发布时间】:2018-05-16 10:01:16
【问题描述】:

我正在编写一个从 Azure Blob 存储上传/下载项目的服务。当我上传文件时,我设置了 ContentType

public async Task UploadFileStream(Stream filestream, string filename, string contentType)
{
    CloudBlockBlob blockBlobImage = this._container.GetBlockBlobReference(filename);
    blockBlobImage.Properties.ContentType = contentType;
    blockBlobImage.Metadata.Add("DateCreated", DateTime.UtcNow.ToLongDateString());
    blockBlobImage.Metadata.Add("TimeCreated", DateTime.UtcNow.ToLongTimeString());
    await blockBlobImage.UploadFromStreamAsync(filestream);
}

但是,当我检索文件时,ContentType 为空。

public async Task<CloudBlockBlob> GetBlobItem(string filename)
{
    var doesBlobExist = await this.DoesBlobExist(filename);
    return doesBlobExist ? this._container.GetBlockBlobReference(filename) : null;
}

在使用这些方法的代码中,我检查了返回的 Blob 的 ContentType,但它为空。

var blob = await service.GetBlobItem(blobname);
string contentType = blob.Properties.ContentType; //this is null!

我曾尝试在我的 UploadFileStream() 方法(上图)中使用 SetProperties() 方法,但这也不起作用。

CloudBlockBlob blockBlobImage = this._container.GetBlockBlobReference(filename);
blockBlobImage.Properties.ContentType = contentType;
blockBlobImage.SetProperties(); //adding this has no effect
blockBlobImage.Metadata.Add("DateCreated", DateTime.UtcNow.ToLongDateString());
blockBlobImage.Metadata.Add("TimeCreated", DateTime.UtcNow.ToLongTimeString());
await blockBlobImage.UploadFromStreamAsync(filestream);

那么如何为 Azure Blob 存储中的 Blob 项设置 ContentType

【问题讨论】:

  • 可以分享this.DoesBlobExist方法的代码吗?
  • 删除本质上是错误检查代码 -- return await this._container.GetBlockBlobReference(filename).ExistsAsync();
  • ExistsAsync 的问题在于它返回一个Task&lt;bool&gt;。您需要能够进行网络调用并返回 Task&lt;CloudBlockBlob&gt; 的东西。

标签: azure azure-storage azure-blob-storage


【解决方案1】:

问题出在以下代码行:

this._container.GetBlockBlobReference(filename)

基本上这会在客户端创建一个CloudBlockBlob 的实例。它不进行任何网络调用。因为此方法只是在客户端创建一个实例,所以所有属性都使用默认值进行初始化,这就是为什么您会看到 ContentType 属性为 null。

您需要做的实际上是进行网络调用以获取 blob 的属性。您可以在 CloudBlockBlob 对象上调用FetchAttributesAsync() 方法,然后您将看到ContentType 属性正确填写。

请记住,FetchAttributesAsync 方法可能会引发错误(例如,如果 blob 不存在,则为 404),因此请确保对该方法的调用包含在 try/catch 块中。

你可以试试下面的代码:

public async Task<CloudBlockBlob> GetBlobItem(string filename)
{
  try
  {
    var blob = this._container.GetBlockBlobReference(filename);
    await blob.FetchAttributesAsync();
    return blob;
  }
  catch (StorageException exception)
  {
    return null;
  }
}

【讨论】:

  • 我已经在做一些非常相似的事情,但没有 FetchAttributeAsync()。这非常有效,所以我将其标记为答案。非常感谢:)
猜你喜欢
  • 2020-02-08
  • 2018-07-11
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 2020-05-13
  • 1970-01-01
  • 2019-04-03
相关资源
最近更新 更多