Upload file to Azure Blob from HTML webpage (C#)?

1.2k views Asked by At

I am trying to figure out how to take a file from an html form and save it to my Azure Blob storage. I have found many posts about doing this for JavaScript but I am trying to do it via C#. One source I found said to do

using (YourFileUpload.PostedFile.InputStream) { blockBlob.UploadFromStream((FileStream)YourFileUpload.PostedFile.InputStream); }

but PostedFile does not exist in the HttpPostedFileBase object.

The code I have built out so far is

    public static int UploadFile(string FileName, HttpPostedFileBase UploadedFile, int ExistingFileID = 0)
    {
        var StorageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"].ToString());
        var BlobClient = StorageAccount.CreateCloudBlobClient();
        var Container = BlobClient.GetContainerReference("ffinfofiles");
        var BlobBlock = Container.GetBlockBlobReference(FileName);
        var FileExtension = Path.GetExtension(UploadedFile.FileName.ToLower());

        using (UploadedFile.InputStream)
        {
            BlobBlock.UploadFromStream((FileStream)UploadedFile.InputStream);
        }

but when I run this I get the error:

Unable to cast object of type 'System.Web.HttpInputStream' to type 'System.IO.FileStream'.

What method do I need to do so I can upload the file to the Azure Blob?

1

There are 1 answers

2
Serdar Ozler On BEST ANSWER

You should not try to cast UploadedFile.InputStream to a FileStream. CloudBlockBlob.UploadFromStream requires a Stream object, so it should be able to work directly with UploadedFile.InputStream.