在Azure Blob存储项上设置ContentType

时间:2018-05-16 10:01:16

标签: azure azure-storage azure-storage-blobs

我正在编写一个从 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 ,但它是null。

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

1 个答案:

答案 0 :(得分: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;
  }
}