Progress will discontinue Telerik Platform on May 10th, 2018. Learn more

Tutorial: Uploading an Image from the Gallery

Tutorial: Uploading an Image from the Gallery

In this article, you will learn how to use the SDK methods to upload an image file to Telerik Platform, then acquire its download URL from Telerik Platform and finally display it on the device's screen.

The examples in this section assume that you are in the context of a Windows Phone App and that you have basic familiarity with Windows Phone development.

Steps at a glance:

  1. Download and Add the SDK to Your Project
  2. Initialize the Everlive Instance
  3. Prepare the App UI
  4. Add a Method for Uploading a File
  5. Add a Method for Reading a File
  6. Add an Image Picker to the App
  7. Upload and Display the Image
  8. Run the App

Prerequisites

  • A Telerik Platform account.
  • The App ID for your Telerik Platform app. You can access it from Settings.
  • The Data service enabled.
  • A .NET Framework version that supports Task-based Asynchronous Pattern (TAP) programming with async and await. Learn more in Asynchronous Execution.

Download and Add the SDK to Your Project

  1. Log in to your Telerik Platform account and click Getting Started > Downloads in the top right corner.
  2. Under Download SDKs & Tools click Backend Services to see a list of available downloads.
  3. Follow the instructions on the page to download a ZIP archive containing the .NET SDK to your local machine.

    Downloads overview image

  4. Unzip the archive and reference the .dll SDK file in your project.

  5. Add the following statements to reference the required namespaces from the SDK:
using Telerik.Everlive.Sdk.Core;
using Telerik.Everlive.Sdk.Core.Model.Result;
using Telerik.Everlive.Sdk.Core.Query.Definition.FormData;
Imports Telerik.Everlive.Sdk.Core
Imports Telerik.Everlive.Sdk.Core.Model.Result
Imports Telerik.Everlive.Sdk.Core.Query.Definition.FormData

Initialize the Everlive Instance

The Everlive object connects the client app to a Telerik Platform app. To initialize it and to specify your App ID value, add these literals as fields of your page class:

private const string appId = "your-app-id";
//set UseHttps = false to use HTTP
private static EverliveAppSettings appSettings = new EverliveAppSettings() { AppId = appId, UseHttps = true };
private static EverliveApp app = new EverliveApp(appSettings);
Private Const appId As String = "your-app-id"
Private Shared appSettings As New EverliveAppSettings() With { _
    Key .AppId = appId, _
    Key .UseHttps = True _ 'set to false to use HTTP
}
Private Shared app As New EverliveApp(appSettings)

Prepare the App UI

After configuring the project it is time to build a simple UI for your app. The following Extensible Application Markup Language (XAML) markup creates a couple of controls on the page—a Button and an Image.

<StackPanel>
    <Image Width="400" Height="200" Name="myImage" Stretch="Uniform" />
    <Button Tap="Button_Tap">Pick an Image</Button>
</StackPanel>

When the button is tapped, the Button_Tap event handler uploads the image to Telerik Platform, gets its URI, and then displays it in the Image control. You will define the handler body later.

Add a Method for Uploading a File

After setting up the UI, your next step is implementing an UploadFile method that uses the Upload SDK method for uploading a file from a binary stream to Telerik Platform:

private async Task<CreateResultItem> UploadFile(EverliveApp app, string fileName, string contentType, Stream fileStream)
{
    var fileField = new FileField();
    fileField.FileName = fileName;
    fileField.ContentType = contentType;
    fileField.InputStream = fileStream;

    return await app.WorkWith().Files().Upload(fileField).ExecuteAsync();
}
Private Async Function UploadFile(app As EverliveApp, fileName As String, contentType As String, fileStream As Stream) As Task(Of CreateResultItem)
    Dim fileField = New FileField()
    fileField.FileName = fileName
    fileField.ContentType = contentType
    fileField.InputStream = fileStream

    Return Await app.WorkWith().Files().Upload(fileField).ExecuteAsync()
End Function

Add a Method for Reading a File

After uploading a file to Telerik Platform, you need to read its metadata that contains the image URI to take further actions. In this case you will be using the URI to display the image on the screen.

The following SDK method reads file metadata by ID from Telerik Platform:

 private async Task<Telerik.Everlive.Sdk.Core.Model.System.File> GetFileMetadataById(EverliveApp app, Guid fileId)
{
    return await app.WorkWith().Files().GetById(fileId).ExecuteAsync();
}
Private Async Function GetFileMetadataById(app As EverliveApp, fileId As Guid) As Task(Of Telerik.Everlive.Sdk.Core.Model.System.File)
    Return Await app.WorkWith().Files().GetById(fileId).ExecuteAsync()
End Function

Add an Image Picker to the App

Before you can upload an image, you need to acquire it. The following Button_Tap event handler uses the PhotoChooserTask task that allows the user to pick an image from the image gallery or to take a camera photo.

private void Button_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
    PhotoChooserTask photoChooserTask = new PhotoChooserTask();
    photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
    photoChooserTask.ShowCamera = true;
    photoChooserTask.Show();
}
Private Sub Button_Tap(sender As Object, e As System.Windows.Input.GestureEventArgs)
    Dim photoChooserTask As New PhotoChooserTask()
    photoChooserTask.Completed += New EventHandler(Of PhotoResult)(photoChooserTask_Completed)
    photoChooserTask.ShowCamera = True
    photoChooserTask.Show()
End Sub

When the PhotoChooserTask completes successfully, the photoChooserTask_Completed event handler is executed. You will use this event handler to upload the image and display it back on the device.

Upload and Display the Image

In this step you call the UploadFile and GetFileMetadataById methods that were implemented earlier to upload and read file metadata from Telerik Platform.

When the file is uploaded, the server returns its Id and CreatedAt system fields. Then the code uses Id to obtain the file URI. Finally, it downloads the image from the URI and displays it in the Image control.

private async void photoChooserTask_Completed(object sender, PhotoResult e)
{
    if (e.TaskResult == TaskResult.OK)
    {
        Stream imageStream = e.ChosenPhoto;
        string imageFilename = e.OriginalFileName;
        string imageContentType = "image/jpeg"; 

        var imageUploadResult = await UploadFile(everliveApp, imageFilename, imageContentType, imageStream);

        imageStream.Close();

        var fileId = imageUploadResult.Id;

        var imageMetadataResult = await GetFileMetadataById(everliveApp, fileId);

        var imageUri = imageMetadataResult.Uri;

        this.Dispatcher.BeginInvoke(delegate
        {
            this.myImage.Source = new BitmapImage(new Uri(imageUri, UriKind.Absolute));
        });
    }
}
Private Async Sub photoChooserTask_Completed(sender As Object, e As PhotoResult)
    If e.TaskResult = TaskResult.OK Then
        Dim imageStream As Stream = e.ChosenPhoto
        Dim imageFilename As String = e.OriginalFileName
        Dim imageContentType As String = "image/jpeg"

        Dim imageUploadResult = Await UploadFile(everliveApp, imageFilename, imageContentType, imageStream)

        imageStream.Close()

        Dim fileId = imageUploadResult.Id

        Dim imageMetadataResult = Await GetFileMetadataById(everliveApp, fileId)

        Dim imageUri = imageResult.Uri

        Me.Dispatcher.BeginInvoke(Sub() Me.myImage.Source = New BitmapImage(New Uri(imageUri, UriKind.Absolute)))
    End If
End Sub

Run the App

Now you are ready to run the app on a physical device on in the emulator.

Start a free trial Request a demo
Contact us: +1-888-365-2779
sales@telerik.com
Copyright © 2016-2017, Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.