How to upload file to azure from C# code by using angular as front end and passing file through the api to api controller

653 Views Asked by At

I'm developing an application wherein the requirement is to upload the file to Azure blob storage. I tried the azure-blob-storage-service plugin which is present in the angular nuget manager.

Can anyone suggest any other approach like uploading it from server side using c#?

1

There are 1 best solutions below

0
Mohit Verma On

Here you can find a good sample on using Angular SPA and web api which allow a user to browse and delete images in an azure storage container as well as uplaod new files.

It also shows how to create web api controller to support the required server side operation

Here is the add method of controller

public async Task<IEnumerable<PhotoViewModel>> Add(HttpRequestMessage request) 
{ 
    CloudBlobClient blobClient = this.StorageAccount.CreateCloudBlobClient(); 
    CloudBlobContainer photoContainer = blobClient.GetContainerReference(this.ContainerName); 

    var provider = new AzureBlobMultipartFormDataStreamProvider(photoContainer); 

    await request.Content.ReadAsMultipartAsync(provider); 

    var photos = new List<PhotoViewModel>(); 

    foreach (var file in provider.FileData) 
    { 
        //the LocalFileName is going to be the absolute Uri of the blob (see GetStream) 
        //use it to get the blob info to return to the client 
        var blob = await photoContainer.GetBlobReferenceFromServerAsync(file.LocalFileName); 
        await blob.FetchAttributesAsync(); 

        photos.Add(new PhotoViewModel 
        { 
            Name = blob.Name, 
            Size = blob.Properties.Length / 1024, 
            Created = blob.Metadata["Created"] == null ? DateTime.Now : DateTime.Parse(blob.Metadata["Created"]), 
            Modified = ((DateTimeOffset)blob.Properties.LastModified).DateTime, 
            Url = blob.Uri.AbsoluteUri 
        }); 
    } 

    return photos;       
}

It creates an instance of the AzureBlobMultipartFormDataStreamProvider, derived from MultipartFormDataStreamProvider to save the files with their original names the derived class rather using computed names.

public class AzureBlobMultipartFormDataStreamProvider : MultipartFormDataStreamProvider 
{ 
    private CloudBlobContainer BlobContainer { get; set; } 

    public AzureBlobMultipartFormDataStreamProvider(CloudBlobContainer blobContainer): base("azure") 
    { 
        this.BlobContainer = blobContainer; 
    } 

    public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) 
    { 
        if (parent == null) 
        { 
            throw new ArgumentNullException("parent"); 
        } 
        if (headers == null) 
        { 
            throw new ArgumentNullException("headers"); 
        } 

        var fileName = this.GetLocalFileName(headers);; 

        CloudBlockBlob blob = this.BlobContainer.GetBlockBlobReference(fileName); 
        blob.Metadata["Created"] = DateTime.Now.ToString(); 

        if (headers.ContentType != null) 
        { 
            blob.Properties.ContentType = headers.ContentType.MediaType; 
        } 

        this.FileData.Add(new MultipartFileData(headers, blob.Name)); 

        return blob.OpenWrite();             
    } 

    public override Task ExecutePostProcessingAsync() 
    {    

        return base.ExecutePostProcessingAsync(); 
    } 

    public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) 
    { 
        //Make the file name URL safe and then use it & is the only disallowed url character allowed in a windows filename 
        var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName"; 
        return name.Trim(new char[] { '"' }) 
                    .Replace("&", "and"); 
    } 
}

Hope it helps.

https://code.msdn.microsoft.com/windowsapps/AngularJS-with-Web-API-c05b3511/file/134548/3/AngularJS%20with%20Web%20API%20uploading%20files%20to%20Azure%20storage.zip