Home > Software engineering >  Setting content type using BlobServiceClient
Setting content type using BlobServiceClient

Time:03-16

I'm using Azure.Storage.Blobs library v12 to upload files to my Azure Blob Storage container.

It's working fine but I haven't been able to figure out a way to set the content-type for the file.

I found some documentation but the intellisense is not giving me any options to set BlobHttpHeaders. How do I set the content type for the file I upload?

Here's my code

public class StorageService : IStorageService
{
    private string containerName = "my-container";
    private static string connectionString = "my-connection-string";
    private readonly BlobServiceClient _client;

    public StorageService()
    {
        _client = new BlobServiceClient(connectionString);
    }

    public async Task<string> UploadFile(string filePath, string fileName)
    {
        try
        {
            // Generate a unique name for the blob we're uploading
            var blobName = Guid.NewGuid().ToString()   "__"   fileName;

            var _blobContainerClient = _client.GetBlobContainerClient(containerName);

            using (var fileStream = File.OpenRead(filePath))
                await _blobContainerClient.UploadBlobAsync(blobName, fileStream).ConfigureAwait(false);

            return blobName;
        }
        catch
        {
            throw new Exception();
        }
    }
}

CodePudding user response:

Try

try
{
// Generate a unique name for the blob we're uploading
var blobName = Guid.NewGuid().ToString()   "__"   fileName;
var _blobContainerClient = _client.GetBlobContainerClient(containerName);

BlobClient blob = _blobContainerClient.GetBlobClient(fileName);

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);
}
}
catch
{
  throw new Exception();
}

please check this too : check

  • Related