【问题标题】:Xamarin Android WebView download file does nothingXamarin Android WebView 下载文件什么都不做
【发布时间】:2017-05-02 12:50:54
【问题描述】:

我有一个 webview,它显示了一个我没有制作的网站,所以我不知道它是如何工作的细节。

在这个网站上有几个按钮可以下载各种动态生成的文件。以下是在这些按钮之一上使用的 url 请求示例:test.example.com/Test/Export/Stuff?format=Pdf

这会导致在我的桌面浏览器和手机 chrome 上下载文件,但在我的应用程序上没有任何反应。

我已经在互联网上搜索了一个解决方案,但我无法找到一个有效的解决方案。

我已尝试按照此处所述设置 DownloadListener:https://forums.xamarin.com/discussion/4605/download-file-by-webview,但 OnDownloadStart 永远不会触发。

我还尝试在我的自定义 WebViewClient 中使用 ShouldOverrideUrlLoading 拦截 url 请求,如其他帖子中所述,但没有运气。

这里是按钮的html代码:

<input id="exportPdfButton" class="secondary hover" format="Pdf" value="Download (PDF)" name="exportPdfButton" type="submit">
<script id="dxss_848651839" type="text/javascript">

<!--

var dxo = new MVCxClientButton('exportPdfButton');
dxo.InitGlobalVariable('exportPdfButton');
dxo.SetProperties({'autoPostBack':true,'isNative':true});
dxo.SetEvents({'Click':ExportButtonOnClick});
dxo.AfterCreate();

//-->
</script>

我已经为 ACCESS_DOWNLOAD_MANAGER、WRITE_EXTERNAL_STORAGE 等设置了权限。

谁能帮我弄清楚如何在应用程序中下载这些文件?否则我可以提供任何其他信息来提供帮助吗?

【问题讨论】:

  • 当您执行 POST 以启动下载时,下载似乎存在问题。我也有同样的问题。下载管理器似乎仅在您使用 GET 调用下载时才起作用。

标签: android webview xamarin.android


【解决方案1】:

谁能帮我弄清楚如何在应用程序中下载这些文件?

首先,请确保您的WebView 已启用 javascript 并且 WebViewClient 设置正确:

mWebview = FindViewById<WebView>(Resource.Id.mWebview);
mWebview.Download += MWebview_Download;
var client = new WebViewClient();
mWebview.Settings.JavaScriptEnabled = true;
mWebview.SetWebViewClient(client);

mWebview.LoadUrl("your url");

然后在WebView.Download事件中使用DownloadManager下载文件:

private void MWebview_Download(object sender, DownloadEventArgs e)
{
    var url = e.Url;
    DownloadManager.Request request = new DownloadManager.Request(Uri.Parse(url));

    request.AllowScanningByMediaScanner();
    request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted); //Notify client once download is completed!
    request.SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, "CPPPrimer");
    DownloadManager dm = (DownloadManager)GetSystemService("download");
    dm.Enqueue(request);
    Toast.MakeText(ApplicationContext, "Downloading File",ToastLength.Long//To notify the Client that the file is being downloaded
                ).Show();
    }

【讨论】:

  • 是的,我已经启用了 javascript 并设置了客户端。我已经尝试了 .Download 事件,它只是在单击按钮时不会触发。
  • 那么很可能是js脚本的问题。可以发一下Download(PDF)的js函数吗?
  • 它似乎没有使用 javascript,我必须承认我是 JavaScript 的新手。但据我所见,它在包含表单中使用了 Post 。
  • 这正是问题所在,webview 不允许您访问 http 响应的内容。请参考this case。因此,您应该使用HttpClient,而不是使用 webview。
  • 我已经尝试过上述解决方案。它返回损坏的 PDF 文件,但我无法打开该文件。它显示一条错误消息“无法打开 PDF”。我的手机上安装了 PDF 阅读器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 2012-09-11
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 2021-12-23
相关资源
最近更新 更多