Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting content type with BlobContainerClient.UploadBlobAsync()

Tags:

c#

azure

These two posts looked promising:

How upload blob in Azure Blob Storage with specified ContentType with .NET v12 SDK?

Uploading blockblob and setting contenttype

But in both, they are using different libraries. (Why are there so many?) As mandated by powers out of my control, we are using BlobContainerClient. And within that class, we are using the UploadBlobAsync method.

public async Task<string> UploadAsync(string fileName, byte[] file, string containerName)
{
    ...
    BlobContainerClient container = await createContainerIfNotExistsAsync(containerName);
    using Stream stream = file.ToStream();
    var result = await container.UploadBlobAsync(fileName, stream);  // <-- does the upload.
    ...
}

By default, the type is set to application/octet-stream. How can I override this?

like image 872
Casey Crookston Avatar asked Dec 22 '22 18:12

Casey Crookston


1 Answers

Ok, figured it out. There are two ways you can upload a file to blob storage.

The first is how I was doing it, which was by bypassing the creation of the BlobClient. See the OP for an example.

The second looks like this:

public async Task<string> UploadAsync(string fileName, byte[] file, string containerName)
{
    ...
    BlobContainerClient container = await createContainerIfNotExistsAsync(containerName);
    BlobClient blobClient = container.GetBlobClient(fileName);
    using Stream stream = file.ToStream();
    var result = await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = "text/plain" });
    ...
}
like image 170
Casey Crookston Avatar answered Mar 05 '23 16:03

Casey Crookston