Xamarin.Forms - Upload Image To Blob Storage

In this article you will learn how you can upload Images to blob storage through Xamarin.

Introduction

 
Last time, I published an article with the title “Upload Image to blob storage using Xamarin.Android”. In this article, you will learn how you can upload Images to blob storage through Xamarin.forms. I hope you will learn something amazing in xamarin.
 
Blob Storage

So, the first question that comes to mind is: what is blob storage?

Blob stands for Binary Large Object. Azure Blob Storage is a service for storing large amounts of unstructured object data, such as text or binary data. You can use Blob Storage to expose data publicly to the world, or to store application data privately. Related uses of Blob Storage include,

  • Serving images or documents directly to a browser
  • Storing files for distributed access
  • Streaming video and audio
  • Storing data for backup and restore, disaster recovery, and archiving
  • Storing data for analysis by an on-premises or Azure-hosted service

Create a storage account

 
Prerequisites

If you don't have an Azure subscription, create a free account before you begin.

Log in to the Azure portal.

Create a storage account

 
Now you are ready to create your storage account. Every storage account must belong to an Azure resource group. A resource group is a logical container for grouping your Azure services. When you create a storage account, you have the option to either create a new resource group, or use an existing resource group.

To create a general-purpose v2 storage account in the Azure portal, follow these steps:

  1. In the Azure portal, select all services. In the list of resources, type Storage Accounts. As you begin typing, the list filters based on your input. Select Storage Accounts.

  2. On the Storage Accounts window that appears, choose Add.

  3. Select the subscription in which to create the storage account.

  4. Under the Resource group field, select Create new. Enter a name for your new resource group, as shown in the following image.

     

  5. Next, enter a name for your storage account. The name you choose must be unique across Azure. The name also must be between 3 and 24 characters in length, and can include numbers and lowercase letters only.

  6. Select a location for your storage account, or use the default location.

  7. Leave these fields set to their default values,

    FieldValue
    Deployment modelResource Manager
    PerformanceStandard
    Account kindStorageV2 (general-purpose v2)
    ReplicationLocally redundant storage (LRS)
    Access tierHot

  8. Select Review + Create to review your storage account settings and create the account.

  9. Select Create.

Create a container

  • To create a container in the Azure portal, follow these steps:
  • Navigate to your new storage account in the Azure portal.
  • In the left menu for the storage account, scroll to the Blob service section, then select Blobs.
  • Select the + Container button.
  • Type a name for your new container. The container name must be lowercase, must start with a letter or number, and can include only letters, numbers, and the dash (-) character. For more information about container and blob names, see Naming and referencing containers, blobs, and metadata.
  • Set the level of public access to the container. The default level is Private (no anonymous access).
  • Select OK to create the container.

     

Let’s create a xamarin.forms project with .Net standard library.

First of all add the required nuget packages to our application.

  1. Xam.Plugin.Media
  2. WindowsAzure.Storage
Step 1 - Create User Interface of App

Open MainPage.xaml file, simply replace the following code inside your ContentPage tages.

  1.     <Grid>  
  2.         <Grid.ColumnDefinitions>  
  3.             <ColumnDefinitionWidth="*" />  
  4.         </Grid.ColumnDefinitions>  
  5.         <Grid.RowDefinitions>  
  6.             <RowDefinitionHeight="*" />  
  7.         </Grid.RowDefinitions>  
  8.         <Buttonx:Name="btnSelectPic"Grid.Row="0"Grid.Column="0"Text="Select picture" Clicked="btnSelectPic_Clicked" BackgroundColor="DodgerBlue" TextColor="White" />  
  9.         <Buttonx:Name="btnTakePic"Grid.Row="0"Grid.Column="1"Text="Take picture" Clicked="btnTakePic_Clicked" BackgroundColor="DodgerBlue" TextColor="White" />  
  10.     </Grid>  
  11.     <Imagex:Name="imageView"HeightRequest="300"WidthRequest="400" />  
  12.     <ActivityIndicatorx:Name="uploadIndicator"IsVisible="False" IsRunning="False" Color="DodgerBlue" />  
  13.     <ButtonText="Upload to Blob"Clicked="btnUpload_Clicked" x:Name="btnUpload" BackgroundColor="Green" TextColor="White" />  
  14.   <Editorx:Name="UploadedUrl"TextColor="Black"HeightRequest="85" Text="Image URL:" />  
  15. </StackLayout>   

Step 2 - Write Backend Code

Open your MainPage.xaml.cs file, replace the following code inside your ContentPage tages.
 
Note
In the upload function, I am using my own blob storage connection string. But you will use your own blob storage connection string. Go to Access keys inside this tab you will get two keys (key1 and key2) with also connection strings. You can use either key1 or key2. In this demo we only need the connection string, so you will only copy the connection string.
  1. public partial class MainPage : ContentPage  
  2.     {  
  3.         public MainPage()  
  4.         {  
  5.             InitializeComponent();  
  6.         }  
  7.         private MediaFile _mediaFile;  
  8.         private string URL { get; set; }  
  9.   
  10.         //Picture choose from device    
  11.         private async void btnSelectPic_Clicked(object sender, EventArgs e)  
  12.         {  
  13.             await CrossMedia.Current.Initialize();  
  14.             if (!CrossMedia.Current.IsPickPhotoSupported)  
  15.             {  
  16.                 await DisplayAlert("Error""This is not support on your device.""OK");  
  17.                 return;  
  18.             }  
  19.             else  
  20.             {  
  21.                 var mediaOption = new PickMediaOptions()  
  22.                 {  
  23.                     PhotoSize = PhotoSize.Medium  
  24.                 };  
  25.                 _mediaFile = await CrossMedia.Current.PickPhotoAsync();  
  26.                 if (_mediaFile == null) return;  
  27.                 imageView.Source = ImageSource.FromStream(() => _mediaFile.GetStream());  
  28.                 UploadedUrl.Text = "Image URL:";  
  29.             }  
  30.         }  
  31.   
  32.         //Upload picture button    
  33.         private async void btnUpload_Clicked(object sender, EventArgs e)  
  34.         {  
  35.             if (_mediaFile == null)  
  36.             {  
  37.                 await DisplayAlert("Error""There was an error when trying to get your image.""OK");  
  38.                 return;  
  39.             }  
  40.             else  
  41.             {  
  42.                 UploadImage(_mediaFile.GetStream());  
  43.             }  
  44.         }  
  45.   
  46.         //Take picture from camera    
  47.         private async void btnTakePic_Clicked(object sender, EventArgs e)  
  48.         {  
  49.   
  50.             await CrossMedia.Current.Initialize();  
  51.             if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)  
  52.             {  
  53.                 await DisplayAlert("No Camera"":(No Camera available.)""OK");  
  54.                 return;  
  55.             }  
  56.             else  
  57.             {  
  58.                 _mediaFile = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions  
  59.                 {  
  60.                     Directory = "Sample",  
  61.                     Name = "myImage.jpg"  
  62.                 });  
  63.   
  64.                 if (_mediaFile == null) return;  
  65.                 imageView.Source = ImageSource.FromStream(() => _mediaFile.GetStream());  
  66.                 var mediaOption = new PickMediaOptions()  
  67.                 {  
  68.                     PhotoSize = PhotoSize.Medium  
  69.                 };  
  70.                 UploadedUrl.Text = "Image URL:";  
  71.             }  
  72.         }  
  73.   
  74.         //Upload to blob function    
  75.         private async void UploadImage(Stream stream)  
  76.         {  
  77.             Busy();  
  78.             var account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=ahsanblobaccount;AccountKey=fOvpvzb8jFL0pNfDWvz9n76DzLWSlZu4aw6ZLXMbDId15YYfox15UoKvWMmTCJ6vcNoyk5w+A==;EndpointSuffix=core.windows.net");  
  79.             var client = account.CreateCloudBlobClient();  
  80.             var container = client.GetContainerReference("images");  
  81.             await container.CreateIfNotExistsAsync();  
  82.             var name = Guid.NewGuid().ToString();  
  83.             var blockBlob = container.GetBlockBlobReference($"{name}.png");  
  84.             await blockBlob.UploadFromStreamAsync(stream);  
  85.             URL = blockBlob.Uri.OriginalString;  
  86.             UploadedUrl.Text = URL;  
  87.             NotBusy();  
  88.             await DisplayAlert("Uploaded""Image uploaded to Blob Storage Successfully!""OK");  
  89.         }  
  90.   
  91.         public void Busy()  
  92.         {  
  93.             uploadIndicator.IsVisible = true;  
  94.             uploadIndicator.IsRunning = true;  
  95.             btnSelectPic.IsEnabled = false;  
  96.             btnTakePic.IsEnabled = false;  
  97.             btnUpload.IsEnabled = false;  
  98.         }  
  99.   
  100.         public void NotBusy()  
  101.         {  
  102.             uploadIndicator.IsVisible = false;  
  103.             uploadIndicator.IsRunning = false;  
  104.             btnSelectPic.IsEnabled = true;  
  105.             btnTakePic.IsEnabled = true;  
  106.             btnUpload.IsEnabled = true;  
  107.         }  
  108.     }  
 
Choose From Moible and Upload
 
 
UWP Choose From Computer and Upload
 
 
Capture From Camera and Upload
 
 
UWP Capture From Webcam and Upload