Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save binary file to blob from httppostedfile

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

like image 269
user1577821 Avatar asked Aug 11 '12 20:08

user1577821


People also ask

How do I move files to Azure Blob Storage?

Click on the ... to the right of the Files box, select one or multiple files to upload from the file system and click Upload to begin uploading the files. To download data, selecting the blob in the corresponding container to download and click Download.

Can I store files in Azure Blob Storage?

Blob storage is designed for: Serving images or documents directly to a browser. Storing files for distributed access. Streaming video and audio.

Which command uploads a file to a storage blob?

You can upload files and directories to Blob storage by using the AzCopy v10 command-line utility.


1 Answers

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);
like image 156
Dennis Burton Avatar answered Sep 28 '22 13:09

Dennis Burton