c# - 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);
我的问题是文件已成功下载,但无法打开。
解决方案
我终于使用了另一种方法,使用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));
}
}
这里唯一的问题是操作系统没有显示其本机下载进度条,也没有在文件下载完成时发出通知
推荐阅读
- python - Python 随机库:从帕累托分布模拟(使用形状和比例参数)
- python - 如何为轮廓图扩展 matplotlib 颜色条?
- reactjs - 如何使用 NextJS 使用 SCSS/CSS 模块在外部定义动态变量
- javascript - 调用服务后显示嵌套对象(数字)
- linux - Android Studio 消耗所有系统 RAM 和交换内存
- java - 如何从传递的有限数量的对象中创建流?
- linux - 如何使用 setcap 启用 setuid 功能
- html - 将倒数计时器居中
- visual-studio-code - 当cmd +单击vscode中的代码时,node_modules文件夹是否有任何方式不会不必要地展开?
- python - 使用 np.logical_or 在 Pandas Dataframe 上拆分应用组合