This content originally appeared on Telerik Blogs and was authored by Dobrinka Yordanova
Want to pick files from the device and visualize them in your mobile and desktop applications? No problem! It’s more than easy with Xamarin.Essentials and Telerik UI for Xamarin controls.
In this blog post, we will go through how to use the FilePicker API. We will implement a sample UI for picking images, pdf documents, and selecting multiple images. But what’s next? We want to visualize these files in our application, so we need proper controls, right? And the Telerik UI for Xamarin suite comes in to help us!
Getting Started With Xamarin.Essentials FilePicker
The FilePicker allows us to pick a single or multiple file from the device more than easily. We need a single NuGet package installed to our existing project or new project—Xamarin.Essentials NuGet package.
Platform Settings
On Android
1. Make sure the Xamarin.Essentials is initialized inside the OnCreate() method of the MainActivity.cs file of the Android project:
Xamarin.Essentials.Platform.Init(
this
, savedInstanceState);
2. For handling runtime permissions on Android, inside the MainActivity.cs file—override the OnRequestPermissionsResult() method:
public
override
void
OnRequestPermissionsResult(
int
requestCode,
string
[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base
.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
3. Grant permissions to read data from the external storage. We can use one of the following options:
- Open the AssemblyInfo.cs file located inside the Properties folder and add the following code:
[assembly: UsesPermission(Android.Manifest.Permission.ReadExternalStorage)]
- Open the AndroidManifest.xml file inside the Properties folder and add the following inside of the manifest node:
<
uses-permission
android:name
=
"android.permission.READ_EXTERNAL_STORAGE"
/>
Android permissions popup:
✅ iOS and UWP
They don’t require additional setup.
FilePicker API
FilePicker class gives us two methods for picking file(s):
- PickAsync() – gives us the option to pick a single file from the device.
- PickMultipleAsync() – gives us the option to pick multiple files from the device.
Both methods have a parameter PickOptions for specifying additional information like:
- PickerTitle – which is only used on Android platform
- FileTypes with predefined types like Images, Png, Jpeg, Videos, Pdf
var seletedImage = await FilePicker.PickAsync(
new
PickOptions
{
FileTypes = FilePickerFileType.Images,
PickerTitle =
"Select an image"
});
Of course, we can specify custom file types per platform. For example, if we want the user to be able to pick a .txt file on iOS, a .pdf file on Android, and .txt/.pdf/.docx files on UWP, we’d use the following simple code:
var customFileType =
new
FilePickerFileType(
new
Dictionary<DevicePlatform, IEnumerable<
string
>>
{
{ DevicePlatform.iOS,
new
[] {
".txt"
} },
{ DevicePlatform.Android,
new
[] {
".png"
} },
{ DevicePlatform.UWP,
new
[] {
".docx"
,
".txt"
,
".pdf"
} },
});
var options =
new
PickOptions
{
PickerTitle =
"Please select a comic file"
,
FileTypes = customFileType,
};
var result = await FilePicker.PickAsync(options);
We will use PickAsync() and PickMultipleAsync() methods in our demo.
❗ We must add the following namespace where the FilePicker API is used:
using
Xamarin.Essentials;
Demo Time
This is what the FilePicker demo looks like:
The demo uses the following Telerik UI for Xamarin controls:
- RadTabView for switching between different options—single image, PDF file, and multiple image selection
- RadButton for its Click event, which will open the file picker
- RadPdfViewer for visualizing the selected PDF document
- RadListView for visualizing multiple images
I have added the Telerik UI for Xamarin controls to the project using the Telerik NuGet Server.
Let’s Start With the XAML
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
ContentPage
xmlns
=
"http://xamarin.com/schemas/2014/forms"
xmlns:telerikInput
=
"clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input"
xmlns:telerikPrimitives
=
"clr-namespace:Telerik.XamarinForms.Primitives;assembly=Telerik.XamarinForms.Primitives"
xmlns:telerikPdfViewer
=
"clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.XamarinForms.PdfViewer"
xmlns:telerikDataControls
=
"clr-namespace:Telerik.XamarinForms.DataControls;assembly=Telerik.XamarinForms.DataControls"
xmlns:telerikListView
=
"clr-namespace:Telerik.XamarinForms.DataControls.ListView;assembly=Telerik.XamarinForms.DataControls"
x:Class
=
"FilePickerDemo.MainPage"
>
<
ContentPage.Resources
>
<
ResourceDictionary
>
<
Style
TargetType
=
"telerikPrimitives:TabViewHeaderItem"
>
<
Setter
Property
=
"TextColor"
Value
=
"Black"
/>
<
Setter
Property
=
"SelectedColor"
Value
=
"#0E88F2"
/>
</
Style
>
<
Style
TargetType
=
"telerikInput:RadButton"
>
<
Setter
Property
=
"WidthRequest"
Value
=
"100"
/>
<
Setter
Property
=
"CornerRadius"
Value
=
"15"
/>
<
Setter
Property
=
"Margin"
Value
=
"10"
/>
<
Setter
Property
=
"TextColor"
Value
=
"White"
/>
<
Setter
Property
=
"BackgroundColor"
Value
=
"#0E88F2"
/>
</
Style
>
</
ResourceDictionary
>
</
ContentPage.Resources
>
<
Grid
RowDefinitions
=
"Auto,*"
>
<
Label
Text
=
"Welcome to FilePicker Demo"
HorizontalTextAlignment
=
"Center"
TextColor
=
"Black"
FontSize
=
"36"
/>
<
telerikPrimitives:RadTabView
Grid.Row
=
"1"
IsContentPreserved
=
"True"
IsContentSwipingEnabled
=
"False"
>
<
telerikPrimitives:RadTabView.Items
>
<
telerikPrimitives:TabViewItem
HeaderText
=
"Pick Image"
>
<
telerikPrimitives:TabViewItem.Content
>
<
StackLayout
Margin
=
"10"
>
<
telerikInput:RadButton
Text
=
"Pick Image"
Clicked
=
"OnPickImageClicked"
/>
<
Label
x:Name
=
"PickedImageInfo"
FontSize
=
"16"
Margin
=
"10"
/>
<
Image
x:Name
=
"image"
HeightRequest
=
"200"
WidthRequest
=
"200"
/>
</
StackLayout
>
</
telerikPrimitives:TabViewItem.Content
>
</
telerikPrimitives:TabViewItem
>
<
telerikPrimitives:TabViewItem
HeaderText
=
"Pick Pdf"
>
<
telerikPrimitives:TabViewItem.Content
>
<
Grid
RowDefinitions
=
"Auto,*"
Margin
=
"10"
>
<
telerikInput:RadButton
Text
=
"Pick Pdf Document"
Clicked
=
"OnPickPdfClicked"
/>
<
telerikPdfViewer:RadPdfViewer
x:Name
=
"pdfViewer"
Grid.Row
=
"1"
BackgroundColor
=
"Transparent"
/>
</
Grid
>
</
telerikPrimitives:TabViewItem.Content
>
</
telerikPrimitives:TabViewItem
>
<
telerikPrimitives:TabViewItem
HeaderText
=
"Pick Multiple Images"
>
<
telerikPrimitives:TabViewItem.Content
>
<
Grid
RowDefinitions
=
"Auto,*"
Margin
=
"10"
>
<
telerikInput:RadButton
Text
=
"Pick Multiple Images"
Clicked
=
"OnPickMultipleImagesClicked"
/>
<
telerikDataControls:RadListView
x:Name
=
"listView"
Grid.Row
=
"1"
>
<
telerikDataControls:RadListView.ItemTemplate
>
<
DataTemplate
>
<
telerikListView:ListViewTemplateCell
>
<
telerikListView:ListViewTemplateCell.View
>
<
StackLayout
Margin
=
"10"
>
<
Image
HeightRequest
=
"100"
WidthRequest
=
"100"
VerticalOptions
=
"Center"
Source
=
"{Binding .}"
/>
</
StackLayout
>
</
telerikListView:ListViewTemplateCell.View
>
</
telerikListView:ListViewTemplateCell
>
</
DataTemplate
>
</
telerikDataControls:RadListView.ItemTemplate
>
</
telerikDataControls:RadListView
>
</
Grid
>
</
telerikPrimitives:TabViewItem.Content
>
</
telerikPrimitives:TabViewItem
>
</
telerikPrimitives:RadTabView.Items
>
</
telerikPrimitives:RadTabView
>
</
Grid
>
</
ContentPage
>
As you can see in the XAML, we have a TabView control with three different TabViewItems. Next, let me take you through what each TabViewItem does.
Pick Image
The first tab is for picking a single image from the device. When the Button is clicked, we can pick an image from the device and visualize it in the Image control. Here is the OnPickImageClicked() implemetation:
private
async
void
OnPickImageClicked(
object
sender, System.EventArgs e)
{
try
{
var seletedImage = await FilePicker.PickAsync(
new
PickOptions
{
FileTypes = FilePickerFileType.Images,
PickerTitle =
"Select an image"
});
if
(seletedImage !=
null
)
{
var data = await seletedImage.OpenReadAsync();
PickedImageInfo.Text = $
"The filename: {seletedImage.FileName} and file type: {seletedImage.ContentType}"
;
image.Source = ImageSource.FromStream(() => data);
}
return
;
}
catch
(Exception)
{
}
}
Pick PDF File
The second tab is for picking a pdf document and visualizing it in the RadPdfViewer. Here is the OnPickPdfClicked() implementation.
private
async
void
OnPickPdfClicked(
object
sender, System.EventArgs e)
{
try
{
var selectedFile = await FilePicker.PickAsync(
new PickOptions
{
FileTypes = FilePickerFileType.Pdf,
PickerTitle =
"Select a pdf"
});
if
(selectedFile !=
null
)
{
var data = await selectedFile.OpenReadAsync();
PdfFormatProvider provider =
new
PdfFormatProvider();
RadFixedDocument document = provider.Import(data);
pdfViewer.Source = document;
pdfViewer.IsVisible =
true;
}
return
;
}
catch
(Exception)
{
}
}
Pick Multiple Images
The third tab is for multiple image selection. When the button is clicked, we can select multiple images from the device and visualize them in the RadListView control. Here is the OnPickMultipleImagesClicked() implementation:
private
async
void
OnPickMultipleImagesClicked(
object
sender, EventArgs e)
{
try
{
var selectedImage = await FilePicker.PickMultipleAsync(
new
PickOptions
{
FileTypes = FilePickerFileType.Images,
PickerTitle =
"Select images"
});
var imageList =
new
List<ImageSource>();
if
(selectedImage !=
null
)
{
foreach
(var selected
in
selectedImage)
{
var data = await selected.OpenReadAsync();
imageList.Add(ImageSource.FromStream(()=>data));
}
listView.ItemsSource = imageList;
}
return
;
}
catch
(Exception)
{
}
}
Pick HTML Documents
You can easily pick HTML documents and then visualize them in your desktop and mobile apps using the Telerik RichTextEditor for Xamarin.
Tell Us What You Think
We would love to hear what you think, so should you have any questions and/or comments, please share them in our Telerik UI for Xamarin Feedback Portal.
If you are new to Telerik UI for Xamarin, you can learn more about it via the product page. It comes with a 30-day free trial, giving you some time to explore the toolkit and consider using it for your current or upcoming Xamarin development.
World of .NET Cross-Platform Application Development
We would also like to share with you our preview UI components for .NET MAUI—Telerik UI for .NET MAUI. You can review the available controls and their features in our Telerik UI for .NET MAUI Demo Application.
Happy coding with our controls!
This content originally appeared on Telerik Blogs and was authored by Dobrinka Yordanova
Dobrinka Yordanova | Sciencx (2021-12-13T09:10:00+00:00) Create a File Picker Using Xamarin.Essentials and Telerik UI for Xamarin. Retrieved from https://www.scien.cx/2021/12/13/create-a-file-picker-using-xamarin-essentials-and-telerik-ui-for-xamarin/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.