Upload a file(any doc file ) in xamarin forms

不问归期 提交于 2021-02-05 12:08:14

问题


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.


回答1:


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);
        }
    }


来源:https://stackoverflow.com/questions/39910272/upload-a-fileany-doc-file-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!