我正在编写一个从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 回答
问题在于以下代码行:
基本上,这会在客户端创建
CloudBlockBlob
的实例 . 它不进行任何网络呼叫 . 因为此方法只是在客户端创建实例,所以使用默认值初始化所有属性,这就是为什么您将ContentType
属性视为null .您需要做的是实际进行网络调用以获取blob的属性 . 您可以在CloudBlockBlob对象上调用FetchAttributesAsync()方法,然后您将看到
ContentType
属性已正确填充 .请记住
FetchAttributesAsync
方法可能会抛出错误(例如404,以防blob不存在)所以请确保对此方法的调用包含在try / catch块中 .您可以尝试以下代码: