首页 > 解决方案 > Xamarin Android,使用 CrossDownloadManager 下载文件时指定 MIME 类型

问题描述

我正在尝试使用 url 下载存储在 db 中的文件。

下面是下载的示例代码

var dirMainToCreate = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Constants.AppDirectory);

if (!System.IO.Directory.Exists(dirMainToCreate))
{
    System.IO.Directory.CreateDirectory(dirMainToCreate);
}

var dirContentToCreate = System.IO.Path.Combine(dirMainToCreate, contentdirectory);
if (!System.IO.Directory.Exists(dirContentToCreate))
{
    System.IO.Directory.CreateDirectory(dirContentToCreate);
}    

CrossDownloadManager.Current.PathNameForDownloadedFile = new Func<IDownloadFile, string>(file => {
    return Path.Combine(dirContentToCreate, filename);
});


(CrossDownloadManager.Current as DownloadManagerImplementation).IsVisibleInDownloadsUi = true;

File = CrossDownloadManager.Current.CreateDownloadFile(Constants.Url+"/Files/GetFile?id="+ fileId, new Dictionary { { "Authorization", "Bearer"+this.Token } } );

CrossDownloadManager.Current.Start(File);

我的问题是文件已成功下载,但无法打开。

标签: c#xamarinxamarin.androidmime-types

解决方案


我终于使用了另一种方法,使用WebClient

https://www.c-sharpcorner.com/article/how-to-download-files-in-xamarin-forms/

    public void DownloadFile(string url, string token, string folder)
    {
        string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);
        Directory.CreateDirectory(pathToNewFolder);

        try
        {
            using (WebClient client = new WebClient())
            {
                client.Headers.Add("API_KEY", App.Api_key);
                client.Headers.Add("Authorization", "Bearer " + token);



                using (Stream rawStream = client.OpenRead(url))
                {
                    string fileName = string.Empty;
                    string contentDisposition = client.ResponseHeaders["content-disposition"];
                    if (!string.IsNullOrEmpty(contentDisposition))
                    {
                        string lookFor = "filename=";
                        int index = contentDisposition.IndexOf(lookFor, StringComparison.CurrentCultureIgnoreCase);
                        if (index >= 0)
                            fileName = contentDisposition.Substring(index + lookFor.Length);
                    }

                    string pathToNewFile = Path.Combine(pathToNewFolder, fileName);

                    client.DownloadFile(url, pathToNewFile);

                }
            }

        }
        catch (Exception ex)
        {
            if (OnFileDownloaded != null)
                OnFileDownloaded.Invoke(this, new DownloadEventArgs(false));
        }
    }

这里唯一的问题是操作系统没有显示其本机下载进度条,也没有在文件下载完成时发出通知


推荐阅读