上载xamarin格式的文件(任何doc文件) [英] Upload a file(any doc file ) in xamarin forms

查看:81
本文介绍了上载xamarin格式的文件(任何doc文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何浏览和上传xamarin格式的文件(而非图片)?

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.

推荐答案

首先,您需要具有读写用户电话的权限

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

请求权限如下

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

这篇关于上载xamarin格式的文件(任何doc文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆