点击上方蓝字关注“汪宇杰博客”
导语
前不久我写了一篇《尝鲜新版 Azure .NET SDK》之后,使用了一段时间发现没爆,于是今天决定把博客的图片存储从旧版 SDK 迁移到新版 SDK,结果小收福报。
Content-Type
上传到 Azure Blob 的文件必须设置正确的 Content-Type (Mime Type),要不然就会加班收福报,曾经在我的《.NET Core 批量重置 Azure Blob Storage 的 mime type》解释过。因此,以下代码需要迁移到新版SDK。
var blockBlob = _container.GetBlockBlobReference(fileName);
// Why .NET Core doesn't have MimeMapping.GetMimeMapping()
string extension = Path.GetExtension(blockBlob.Uri.AbsoluteUri);
switch (extension.ToLower())
{
case ".jpg":
case ".jpeg":
blockBlob.Properties.ContentType = "image/jpeg";
break;
case ".png":
blockBlob.Properties.ContentType = "image/png";
break;
case ".gif":
blockBlob.Properties.ContentType = "image/gif";
break;
default:
break;
}
await using (var fileStream = new MemoryStream(imageBytes))
{
await blockBlob.UploadFromStreamAsync(fileStream);
}
新版 SDK 的上传方法很简单,根据 GitHub 的 Readme,一般是这样的:
// Get a reference to a blob named "sample-file" in a container named "sample-container"
BlobClient blob = container.GetBlobClient(blobName);
// Upload local file
blob.Upload(filePath);
传送门:https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/storage/Azure.Storage.Blobs/README.md#uploading-a-blob
那么 ContentType 去哪儿了?我一开始以为它现在能自动根据拓展名设置 ContentType,结果传上去的全是 application/octet-stream,爆到天上去。
新版 SDK 的文档和教程很少,Bing 没有什么卵用。996了半小时后,最终在官网的 API Reference 里找到了疑似对象:BlobHttpHeaders.ContentType
传送门:https://docs.microsoft.com/en-us/dotnet/api/azure.storage.blobs.models.blobhttpheaders.contenttype?WT.mc_id=AZ-MVP-5002809&view=azure-dotnet
而 BlobClient 的 Upload 方法正好有个重载,能接受 BlobHttpHeaders 参数,于是我实验了一下,居然成功了:
BlobClient blob = _container.GetBlobClient(fileName);
// Why .NET Core doesn't have MimeMapping.GetMimeMapping()
var blobHttpHeader = new BlobHttpHeaders();
string extension = Path.GetExtension(blob.Uri.AbsoluteUri);
switch (extension.ToLower())
{
case ".jpg":
case ".jpeg":
blobHttpHeader.ContentType = "image/jpeg";
break;
case ".png":
blobHttpHeader.ContentType = "image/png";
break;
case ".gif":
blobHttpHeader.ContentType = "image/gif";
break;
default:
break;
}
await using (var fileStream = new MemoryStream(imageBytes))
{
var uploadedBlob = await blob.UploadAsync(fileStream, blobHttpHeader);
}
现在上传到 Azure Blob 里的文件能够获得正确的 Content-Type 信息。