Vicky Kunal
Vicky Kunal

Reputation: 13

Upload a file(any doc file ) in xamarin forms

How to browse and upload a file (not a pic) in xamarin forms?

Ex. When i click on button event. its open the file manger of mobile and then pick any doc from mobile and then upload it.

Upvotes: 0

Views: 2438

Answers (1)

Sayo Komolafe
Sayo Komolafe

Reputation: 1008

First off, you need to have permission to read and write to the users phone

Request permission as below

using Plugin.FilePicker;
using Plugin.Permissions;    

async Task<bool> RequestStoragePermission()
    {
        //We always have permission on anything lower than marshmallow.
        if ((int)Android.OS.Build.VERSION.SdkInt < 23)
            return true;

        var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage);
        if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
        {
            Console.WriteLine("Does not have storage permission granted, requesting.");
            var results = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.Storage);
            if (results.ContainsKey(Plugin.Permissions.Abstractions.Permission.Storage) &&
                results[Plugin.Permissions.Abstractions.Permission.Storage] != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
            {
                Console.WriteLine("Storage permission Denied.");
                return false;
            }
        }
        return true;
    }

Then go ahead and create a method to do the picking for you

  public async void AttachDocument(object sender, EventArgs e)
    {
        try
        {
            var requestAccessGrant = await RequestStoragePermission();

            if (requestAccessGrant)
            {
                var filedata = await CrossFilePicker.Current.PickFile();
                if (filedata == null) 
                   return;

                  //writing the filename to our view
                  //SupportingDocument is the x:name of our label in xaml
                SupportingDocument.Text = filedata.FileName;
            }
            else
            {
                await DisplayAlert("Error Occured", "Failed to attach document. please grant access.", "Ok");
            }


        }
        catch (Exception ex)
        {
            Console.WriteLine("Error occured ", ex);
        }
    }

Upvotes: 1

Related Questions