我有一个带有文本框和下载按钮的网页,只要单击该文本框的内容,就会将其下载为文本文件。我可以在Android webview中加载此网页,但是在单击下载按钮时却什么也不做。
因此,我尝试使用android WebView的下载侦听器,此方法在网页开始下载时触发。但是在使用该URI创建DownloadManager.Request时会抛出无效的参数异常。但是,如果我提供了可在线下载的链接(http://25.io/toau/audio/sample.txt),它就可以正常工作。请找到该网页,然后从下面下载侦听器代码。
网页代码
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<html>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=3 cols=50 name="text">Please type in this box. When you
click the Download button, the contents of this box will be downloaded to
your machine at the location you specify. </textarea>
<input type="submit" value="Download">
</form>
</body>
</html>
WeBView代码
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
//for downloading directly through download manager
global::Android.Net.Uri uri = global::Android.Net.Uri.Parse(url);
Request request = new Request(uri);
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted);
request.SetDestinationInExternalPublicDir(Environment.CurrentDirectory, "MyFile.txt");
DownloadManager dm = DownloadManager.FromContext(Forms.Context);
dm.Enqueue(request);
}