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

AprilX picture AprilX · Jun 15, 2016 · Viewed 20.1k times · Source

I am not familiar with azure, or rest api, or c#, but anyway I have to do this and I did not find a good document to guide me...

so there is this web app, currently a webform, not mvc... which is going to be hosted on Azure platform,

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

The files may be pdf or 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 start 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#? This part I really don't know. Is it a silly question?

I am really a beginner and I am grateful for any help, thank you guys (T . T)

Answer

Gary Holland picture Gary Holland · Jun 15, 2016

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

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/