Xamarin.Forms - Upload Image To Blob Storage

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.
 
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
 
 
Create a 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
 
 


Similar Articles