- 用户从URL下载文件(向REST API发出HTTP请求,该API受Basic身份验证保护,用户名:secretKey)
- 文件保存到iOS设备上
- 用户打开文件(允许的格式有jpg、png、pdf、doc、docx、png)
- 文件在默认应用程序中打开(例如图片查看器)
public interface IFileHelper
{
void DownloadFileAndSave(Models.DocumentModel document);
}
Android实现:
public class FileHelper : IFileHelper
{
// download file and view status in download manager
public void DownloadFileAndSave(Models.DocumentModel document)
{
DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Context.DownloadService);
string url = WebApiUtils.GetBaseUrl() + string.Format("Api/v1/Dms/{0}", document.UniqueId);
DownloadManager.Request request = new Android.App.DownloadManager.Request(Android.Net.Uri.Parse(url)));
request.AddRequestHeader("Authorization", "Basic " + WebApiUtils.GetEncodedCredentials(Auth.Users.Current));
var downloadFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
string path = Path.Combine(downloadFile.AbsolutePath, document.FileName);
request.SetDestinationUri(Android.Net.Uri.FromFile(new Java.IO.File(path)));
request.SetMimeType(document.ContentType);
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
dm.Enqueue(request);
}
在Android系统中,文件只是简单地存储在文件系统中,并且默认安装在任何Android设备上的文件浏览器(即我的文件->设备存储->下载)中,该文件会在与文件MIME类型相对应的默认应用程序中打开。在Android上一切都很好。
Apple iOS实现:
public class FileHelper : IFileHelper
{
public void DownloadFileAndSave(Models.DocumentModel document)
{
WebClient webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + WebApiUtils.GetEncodedCredentials(Auth.Users.Current));
webClient.DownloadDataAsync(new System.Uri(WebApiUtils.GetBaseUrl() + string.Format(Consts.ApiUrls.GetDocument, document.UniqueId)));
webClient.DownloadDataCompleted += (sender, e) =>
{
byte[] content = e.Result;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), document.FileName);
// doesn't throw exception therefore saved ok
File.WriteAllBytes(path, content);
Uri uri = new Uri(String.Format("file://{0}", path));
// doesn't work.
Device.OpenUri(uri);
};
}
}
有没有其他方法可以用默认应用程序打开下载的文件?如果我打开网址,例如http://example.com/files/file1.png,它会在safari中打开该文件,但我无法在
Device.OpenUri
中放置Authorization: Basic
标头。我了解到使用WebView加载非Web文档,但您需要将每个文件构建为
BundleResource
。
System.IO.File.Exists(path);
进行了测试。 - broadband