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. //Picture choose from device
  10. private async void btnSelectPic_Clicked(object sender, EventArgs e)
  11. {
  12. await CrossMedia.Current.Initialize();
  13. if (!CrossMedia.Current.IsPickPhotoSupported)
  14. {
  15. await DisplayAlert("Error", "This is not support on your device.", "OK");
  16. return;
  17. }
  18. else
  19. {
  20. var mediaOption = new PickMediaOptions()
  21. {
  22. PhotoSize = PhotoSize.Medium
  23. };
  24. _mediaFile = await CrossMedia.Current.PickPhotoAsync();
  25. if (_mediaFile == null) return;
  26. imageView.Source = ImageSource.FromStream(() => _mediaFile.GetStream());
  27. UploadedUrl.Text = "Image URL:";
  28. }
  29. }
  30. //Upload picture button
  31. private async void btnUpload_Clicked(object sender, EventArgs e)
  32. {
  33. if (_mediaFile == null)
  34. {
  35. await DisplayAlert("Error", "There was an error when trying to get your image.", "OK");
  36. return;
  37. }
  38. else
  39. {
  40. UploadImage(_mediaFile.GetStream());
  41. }
  42. }
  43. //Take picture from camera
  44. private async void btnTakePic_Clicked(object sender, EventArgs e)
  45. {
  46. await CrossMedia.Current.Initialize();
  47. if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
  48. {
  49. await DisplayAlert("No Camera", ":(No Camera available.)", "OK");
  50. return;
  51. }
  52. else
  53. {
  54. _mediaFile = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
  55. {
  56. Directory = "Sample",
  57. Name = "myImage.jpg"
  58. });
  59. if (_mediaFile == null) return;
  60. imageView.Source = ImageSource.FromStream(() => _mediaFile.GetStream());
  61. var mediaOption = new PickMediaOptions()
  62. {
  63. PhotoSize = PhotoSize.Medium
  64. };
  65. UploadedUrl.Text = "Image URL:";
  66. }
  67. }
  68. //Upload to blob function
  69. private async void UploadImage(Stream stream)
  70. {
  71. Busy();
  72. var account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=ahsanblobaccount;AccountKey=fOvpvzb8jFL0pNfDWvz9n76DzLWSlZu4aw6ZLXMbDId15YYfox15UoKvWMmTCJ6vcNoyk5w+A==;EndpointSuffix=core.windows.net");
  73. var client = account.CreateCloudBlobClient();
  74. var container = client.GetContainerReference("images");
  75. await container.CreateIfNotExistsAsync();
  76. var name = Guid.NewGuid().ToString();
  77. var blockBlob = container.GetBlockBlobReference($"{name}.png");
  78. await blockBlob.UploadFromStreamAsync(stream);
  79. URL = blockBlob.Uri.OriginalString;
  80. UploadedUrl.Text = URL;
  81. NotBusy();
  82. await DisplayAlert("Uploaded", "Image uploaded to Blob Storage Successfully!", "OK");
  83. }
  84. public void Busy()
  85. {
  86. uploadIndicator.IsVisible = true;
  87. uploadIndicator.IsRunning = true;
  88. btnSelectPic.IsEnabled = false;
  89. btnTakePic.IsEnabled = false;
  90. btnUpload.IsEnabled = false;
  91. }
  92. public void NotBusy()
  93. {
  94. uploadIndicator.IsVisible = false;
  95. uploadIndicator.IsRunning = false;
  96. btnSelectPic.IsEnabled = true;
  97. btnTakePic.IsEnabled = true;
  98. btnUpload.IsEnabled = true;
  99. }
  100. }
Choose From Moible and Upload
UWP Choose From Computer and Upload
Capture From Camera and Upload
UWP Capture From Webcam and Upload
Source Code Here