3

因此,android 浏览器或 webview 可以很好地处理这样的网址 - abc.com/xyz.txt

但是,如果您的 URL 看起来像这样 - abc.com/xyz.php 并且在标头中发送到浏览器的是 - Content-Disposition: attachment; filename="xyz.txt",那么 Android 浏览器和 web 视图似乎变得非常混乱。

看起来它在手机上保存了正确的文件名,但内容充满了之前正在查看的网页。这在基于 PC 的浏览器以及 iPhone 和 Blackberry 上运行良好,这只是 Android 2.1 和 2.2 上的问题(尚未测试其他版本)。

有人有解决方案吗?将不胜感激。我真的不想开始存储静态文件并想即时生成我的下载内容。手机上的日志没有显示任何线索。


这是服务器发送到浏览器的内容

===================== start content ====================================
HTTP/1.1 200 OK
Date: Thu, 21 Oct 2010 21:22:11 GMT
Server: Apache
Content-Disposition: attachment; filename="Wafty.txt"
Content-length: 30
Content-Type: text/plain; charset=ISO-8859-1

Hello this is a test of a file
========= There was no carriage return at the end of the above line ====
4

2 回答 2

2

利用:

Content-Disposition: attachment;filename="xyz.txt"

不要使用(注意多余的空间):

Content-Disposition: attachment;  filename="xyz.txt"
于 2011-08-29T13:31:49.387 回答
1

我有一个和你类似的问题。这里的问题是 WebView 如何处理附件(真是让人头疼)。当 WebView 访问在某个时候返回附件的网页时,它会说有点像“哦,废话,我能用这个非 HTML 的东西做什么?...嘿你!DownloadListener!用这个 URL 做一些事情就是说关于附件的一些废话”。因此,DownloadListener 接管了问题:它再次请求相同的 URL 来下载附件,因此,为了在访问页面时下载附件,WebView 执行 2 个请求:页面本身,然后是另一个下载附件,而不是仅仅下载它。

这是怎么回事?好吧,假设在您的 abc.com/xyz.php 中,您有一些逻辑,例如:

<?php
   if(User::loggedIn()) {
       header("Content-Disposition: attachment...");
       //Some more logic for the download
   }
?>

DownloadListener 执行的第二个请求将向 abc.com/xyz.php 发出另一个请求,但这次它不包含 cookie 或会话信息,因此它不会进入“下载”逻辑。

一种可能的解决方案是重定向到临时副本或不包含任何逻辑的文件的真实路径,因此没有问题。当然,您还需要使用您的 WebView 定义您的下载侦听器,例如这样的。

webView.setDownloadListener(new DownloadListener() {

    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {

        final DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Request request = new DownloadManager.Request(Uri.parse(url));
        request.setMimeType(mimeType);

        //Persist download notification in the status bar after the download completes (Android 3.0+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }

        dm.enqueue(request);
    }

});
于 2014-10-02T10:07:15.230 回答