Home > other >  How do I automatically set the Content Type of a file uploaded to Blob Storage in .Net?
How do I automatically set the Content Type of a file uploaded to Blob Storage in .Net?

Time:08-24

Description/Code:

I have a file coming in to my endpoint with the content encoded as a Base64 string as such:

{
  "content": "base64String",
  "contentType": "application/pdf"
}

I decode this string, write it to a MemoryStream and upload it to Azure Blob Storage using the Azure SDK for .NET:

var fileByteArray = Convert.FromBase64String(fileRequest.FileContent);
var stream = new MemoryStream();
stream.Write(fileByteArray, 0, fileByteArray.Length);
stream.Position = 0;
await _blobService.UploadAsync("containerName", stream, "fileName");

Using the Azure SDK I create a BlobClient and call UploadAsync

var blobServiceClient = new BlobServiceClient("connectionString");
var blobContainerClient = blobServiceClient.GetBlobContainerClient("containerName");
var blobClient = blobContainerClient.GetBlobClient("fileName");
await blobClient.UploadAsync(fileStream, overwrite);

Problem

However the file always gets uploaded into Blob Storage with the content type "application/octet-stream". On other endpoints where I send a file uploaded from my UI the content type is always set correctly, however these files being sent from an external site to this endpoint do not. For example, endpoints from my UI accept a IFormFile and upload them directly by calling OpenReadStream():

await _blobStorageService.UploadAsync("containerName", file.OpenReadStream(), "fileName");

Attempts at solution

I am able to set the content type making a separate BlobClient call using:

await blobClient.SetHttpHeadersAsync(new BlobHttpHeaders { ContentType = "application/pdf" });

This sets it correctly but making an additional call seems inefficient and I am trying to figure out how to just have the stream uploaded automatically know the content type similar to how files from my UI are.

CodePudding user response:

What you need to do is pass a BlobUploadOptions as the second parameter of Upload method:

var blob1Client = containerClient.GetBlobClient("content.txt"); 
var options = new BlobUploadOptions() {
    Metadata = metadata,
    Tags = tags,
    HttpHeaders = new BlobHttpHeaders() { ContentType = "text/plain" }
};
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("Hi!")))
{
    await blob1Client.UploadAsync(ms,options);  
}
  • Related