Save binary file to blob from httppostedfile Save binary file to blob from httppostedfile azure azure

Save binary file to blob from httppostedfile


This code fragment is based on a production app that pushes photos into blob storage. This approach pulls the stream directly from the HttpPostedFile and hands it directly to the client library for storing into a blob. You should vary a few things based on your application:

  • blobName will likely need to adapted.
  • The connectionstring up to fetching the blob client should be isolated into helper classes
  • Similarly you will likely want a helper for the blob container based on your business logic
  • You may not want the container to be fully publicly accessible. That was just added to show you how to do that if you like
// assuming HttpPostedFile is in a variable called postedFile  var contentType = postedFile.ContentType;var streamContents = postedFile.InputStream;var blobName = postedFile.FileNamevar connectionString = CloudConfigurationManager.GetSetting("YOURSTORAGEACCOUNT_CONNECTIONSTRING");var storageAccount = CloudStorageAccount.Parse(connectionString);var blobClient = storageAccount.CreateCloudBlobClient();var container = blobClient.GetContainerReference("YOURCONTAINERNAME");container.CreateIfNotExist();container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });var blob = container.GetBlobReference(blobName);blob.Properties.ContentType = contentType;blob.UploadFromStream(streamContents);


6 years later it seems Dennis Burton's answer isn't compatible with WindowsAzure.Storage v9.3.2.

For me this works:

IFormFile postedFile = null;var contentType = postedFile.ContentType;var blobName = postedFile.FileName;var connectionString = "YOURSTORAGEACCOUNT_CONNECTIONSTRING";var storageAccount = CloudStorageAccount.Parse(connectionString);var blobClient = storageAccount.CreateCloudBlobClient();var container = blobClient.GetContainerReference("YOURCONTAINERNAME");await container.CreateIfNotExistsAsync();var blob = container.GetBlockBlobReference(blobName);blob.Properties.ContentType = contentType;using (var streamContents = postedFile.OpenReadStream()){    await blob.UploadFromStreamAsync(streamContents);}