Xamarin形式的文件下载 [英] File Download in Xamarin forms

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

问题描述

在Xamarin.Forms项目中,我试图从Blob存储区下载文件,我还需要将其保存在设备本地文件夹中并需要立即将其打开.

In Xamarin.Forms project, I'm trying to download the file from the blob storage, also I need to save it in a device local folder and need to open it immediately.

打开文件时出现此异常 Fil:///LocalFolderUrlOfTheFile通过Intent.getData()在应用程序之外公开

I'm getting this exception while opening the file Fil:///LocalFolderUrlOfTheFile exposed beyond app through Intent.getData()

我仅在大于棉花糖的android版本中遇到此异常.

I'm getting this exception only in android versions which are greater than Marshmallow.

以下是我用来打开文件的代码:

Here are codes which i'm using to opening the file:

public void SaveandOpenFile(byte[] data, string fileName)
    {
        string externalStorageState = global::Android.OS.Environment.ExternalStorageState;
        var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + global::Android.OS.Environment.DirectoryDownloads + "/" + fileName;
        File.WriteAllBytes(externalPath, data);

        Java.IO.File file = new Java.IO.File(externalPath);
        file.SetReadable(true);

        string application = "";
        string extension = Path.GetExtension(externalPath);

        // get mimeTye
        switch (extension.ToLower())
        {
            case ".txt":
                application = "text/plain";
                break;
            case ".doc":
            case ".docx":
                application = "application/msword";
                break;
            case ".pdf":
                application = "application/pdf";
                break;
            case ".xls":
            case ".xlsx":
                application = "application/vnd.ms-excel";
                break;
            case ".jpg":
            case ".jpeg":
            case ".png":
                application = "image/jpeg";
                break;
            default:
                application = "*/*";
                break;
        }

        //Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + filePath);
        Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
        Intent intent = new Intent(Intent.ActionView);
        intent.SetDataAndType(uri, application);
        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

        Forms.Context.StartActivity(intent);
    }

如果我缺少什么,请告诉我.预先感谢!

Please let me know if i'm missing something. Thanks in advance!

推荐答案

您不能在新版本的应用程序外部公开文件.您应该设置一些方法来做到这一点.请按照下列步骤操作:

You can't expose the File outside of your app in new versions. You should setup couple of things to do that. Follow these steps:

步骤1:转到您的android清单文件,并在 application 标签内定义文件提供程序.

Step 1: Goto your android's manifest file and define file providers inside application tags.

<provider android:name="android.support.v4.content.FileProvider" 
android:authorities="${applicationId}.provider" android:exported="false" 
android:grantUriPermissions="true">
    <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>

步骤2:用XML定义提供者路径

Step 2: Define the Provider path in XML

  1. 如果资源"文件夹中不存在,请创建XML文件夹.
  2. 创建一个XML文件(如果完全按照上一步操作,则该文件的名称将为"provider_paths.xml"

步骤3:在您在步骤2中创建的提供商路径XML文件中定义提供商文件路径.

Step 3: Define the Provider file path in Provider Path XML file you created in Step 2

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="files" path="."/>
    <internal-path name="files" path="."/>
    <files-path name="files" path="."/>
</paths>

第4步:下载文件时,应将其保存在第3步中定义的位置.我将文件保存在android的以下根目录中:

Step 4: When you download your file you should save them in location that you defined in Step 3. I save the file in android at root directory below:

root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

步骤5:打开文件,以下是我用来共享的方法.希望您能理解并做出相应的更改:

Step 5: Opening the File, Following is the method that I'm using to share. Hope you understand and make changes on yours accordingly :

    public Task Share(string title, string message, string filePath)
    {
        var extension = filePath.Substring(filePath.LastIndexOf(".",StringComparison.InvariantCultureIgnoreCase) + 1).ToLower();
        var contentType = string.Empty;

        Java.IO.File file=new  Java.IO.File(filePath);
        var apkURI = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName+ ".provider", file);

        switch (extension)
        {
            case "pdf":
                contentType = "application/pdf";
                break;
            case "png":
                contentType = "image/png";
                break;
            default:
                contentType = "application/octetstream";
                break;
        }

        var intent = new Intent(Intent.ActionSend);

        intent.SetFlags(ActivityFlags.GrantReadUriPermission);

        intent.SetType(contentType);
        intent.PutExtra(Intent.ExtraStream, apkURI);
        intent.PutExtra(Intent.ExtraText, string.Empty);
        intent.PutExtra(Intent.ExtraSubject, message ?? string.Empty);


        var chooserIntent = Intent.CreateChooser(intent, title ?? string.Empty);
        chooserIntent.SetFlags(ActivityFlags.ClearTop);
        chooserIntent.SetFlags(ActivityFlags.NewTask);

        context.StartActivity(chooserIntent);

        return Task.FromResult(true);
    }

让我知道您是否需要任何帮助.

Let me know if you need any help.

这篇关于Xamarin形式的文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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