Save binary file to blob from httppostedfile
azure, binary, blob, file-upload
Solution
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.FileName
var 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);
Problem
Can somebody provide code to save an uploaded file to azure blob in binary? I currently use a text save which is incredibly slow on huge files, reading/saving to blob, line by line. ``` Private Function ReadFile(ByVal file As HttpPostedFile) As String Dim result As String = "" Dim objReader As New System.IO.StreamReader(file.InputStream) Do While objReader.Peek() <> -1 result = result & objReader.ReadLine() & vbNewLine Loop Return result End Function ``` Thanks