上传blockblob并设置contenttype

本文关键字:contenttype 设置 blockblob 上传 | 更新日期: 2023-09-27 18:12:04

我使用的是c#中的Microsoft.WindowsAzure.Storage.*库。

这是我上传东西到存储的方式:

// Store in storage
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("...connection string...");
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("pictures");
// Create container if it doesnt exist
container.CreateIfNotExists();
// Make available to everyone
container.SetPermissions(new BlobContainerPermissions
{
    PublicAccess = BlobContainerPublicAccessType.Blob
});
// Save image
CloudBlockBlob blockBlob = container.GetBlockBlobReference("blah.jpg");
blockBlob.UploadFromByteArray(byteArrayThumbnail, 0, byteArrayThumbnail.Length);
blockBlob.Properties.ContentType = "image/jpg";  // *** NOT WORKING ***

我上传到存储的所有东西都以内容类型"application/octet-stream"保存,即使我使用值为"image/jpg"的setter(参见我代码中的最后一行)。

所以问题#1:为什么不工作ContentType setter?

问题#2:如果我使用Windows Azure管理门户,手动更改内容类型为"image/jpg",然后将文件的绝对URI复制到浏览器的地址栏中,按回车键,则jpg文件将被下载而不是显示。这个mime类型不是应该显示而不是下载吗?我该如何改变这一点?

上传blockblob并设置contenttype

实际上你不需要调用SetProperties方法。为了在上传blob时设置内容类型,只需在调用上传方法之前设置ContentType属性。所以你的代码应该是:

// Save image
CloudBlockBlob blockBlob = container.GetBlockBlobReference("blah.jpg");
blockBlob.Properties.ContentType = "image/jpg";
blockBlob.UploadFromByteArray(byteArrayThumbnail, 0, byteArrayThumbnail.Length);

,这样就可以了

在您对Properties进行任何更改之后,您必须调用CloudBlockBlob.SetProperties()来实际保存这些更改。

可以把它看作类似于LINQ-to-Entities的东西。您可以对本地对象进行任何更改,但是在调用SaveChanges()之前,实际上没有保存任何内容。

使用新的SDK Azure.Storage.Blobs

BlobHttpHeaders blobHttpHeaders = new BlobHttpHeaders();
blobHttpHeaders.ContentType = "image/jpg";
blobClient.SetHttpHeaders(blobHttpHeaders);

不幸的是,这里提供的答案目前都不适用于最新的SDK (12.x.+)

对于最新的SDK,内容类型应该通过BlobHttpHeaders设置。

var _blobServiceClient = new BlobServiceClient("YOURCONNECTIONSTRING");
var containerClient = _blobServiceClient.GetBlobContainerClient("YOURCONTAINERNAME");
var blob = containerClient.GetBlobClient("YOURFILE.png");
var blobHttpHeader = new BlobHttpHeaders();
blobHttpHeader.ContentType = "image/png";
var uploadedBlob = await blob.UploadAsync(YOURSTREAM, blobHttpHeader);

显然最好设置为创建Gaurav Mantri的答案,如果你超过了这个点,需要更新这里的其他答案可能会把你搞砸。

// GET blob
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); 
// if you don't do this you'll wipe properties you didn't mean to
await blockBlob.FetchAttributesAsync();
// SET
blockBlob.Properties.ContentType = mimetype;
// SAVE
await blockBlob.SetPropertiesAsync();

对于Azure Blob SDK的新版本,这不再工作。

this works for me:

CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference(blobName);
blockBlob.Properties.ContentType = contentType;                            
await blockBlob.SetPropertiesAsync();