Search code examples
c#asp.netrestazure-storageazure-web-app-service

upload files to Azure file storage from web app using rest api


I have a web app that is currently using webforms, not MVC, which is going to be hosted on the Azure platform.

The main function of this web app is to upload user files to Azure File Storage.

The files may be pdf, mp3, etc., not simple text or data stream or data input.

I am told to use Azure REST API to upload files, but I am really not familiar with it and can't find a good sample or tutorial or video online. The current documents from Microsoft reads like ?????? to me.

Currently I just upload to a local folder, so the code looks like: FileUpload1.PostedFile.SaveAs(Server.MapPath("fileupload\\" + FileUpload1.FileName)); in C#;

Where do I go from there? I think I am supposed to add a StorageConnectionString which looks like DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=yyy, which I already have.

And then I should write some code like 'post' in C#?


Solution

  • Azure provide a nuget library that you can use to upload, and do other "file management" types of activities on Azure File Storage.

    The library is called: WindowsAzure.Storage

    UPDATE: The new library to use is Azure.Storage.Blobs.

    Here are the basics of getting this going:

    //Connect to Azure
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
    
    // Create a reference to the file client.
    CloudFileClient fileClient = storageAccount.CreateCloudFileClient();      
    
    // Create a reference to the Azure path
    CloudFileDirectory cloudFileDirectory = GetCloudFileShare().GetRootDirectoryReference().GetDirectoryReference(path);
    
    //Create a reference to the filename that you will be uploading
    CloudFile cloudFile = cloudSubDirectory.GetFileReference(fileName);
    
    //Open a stream from a local file.
    Stream fileStream= File.OpenRead(localfile);
    
    //Upload the file to Azure.
    await cloudFile.UploadFromStreamAsync(fileStream);
    fileStream.Dispose();
    

    More links and info here (note scroll a fair way down for samples): https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-files/