【问题标题】:Download files with Android Webview使用 Android Webview 下载文件
【发布时间】:2014-07-22 08:34:46
【问题描述】:

我正在制作一个使用 WebView 访问网页的 Android 应用程序。为了处理下载,我在 WebView 的 DownloadListener 的 onDownloadStart 方法中使用了 AsyncTask。但是下载的文件是空白的(尽管文件名和扩展名是正确的)。我的 Java 代码是这样的:

protected String doInBackground(String... url) {  
    try {
        URL url = new URL(url[0]);    

        //Creating directory if not exists

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);        
        connection.connect();

        //Obtaining filename

        File outputFile = new File(directory, filename);
        InputStream input   = new BufferedInputStream(connection.getInputStream());
        OutputStream output = new FileOutputStream(outputFile);

        byte data[] = new byte[1024];
        int count = 0;
        Log.e(null, "input.read(data) = "+input.read(data), null);
        while ((count = input.read(data)) != -1) {
            output.write(data, 0, count);
        }              
        connection.disconnect();
        output.flush();
        output.close();
        input.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }
    return null;
}

log.e 行为 input.read(data) 提供 -1 值。 下载页面的 PHP 代码是这个(适用于所有平台)。文件存储在我的 HTML 服务器的非公共目录中。

<?php
$guid = $_GET['id'];
$file = get_file($guid);

if (isset($file['path'])) { 
    $mime = $file['MIMEType'];
    if (!$mime) {
        $mime = "application/octet-stream";
    }

    header("Pragma: public");
    header("Content-type: $mime");
    header("Content-Disposition: attachment; filename=\"{$file['filename']}\"");
    header('Content-Transfer-Encoding: binary');

    ob_clean();
    flush();
    readfile($file['path']);
    exit();

}
?>

我注意到如果我在 PHP 文件的 "?>" 之后写一些文本,该文本会写入下载的文件中。

【问题讨论】:

  • 你的问题/确切的问题是什么?
  • 我的问题是我用我的应用程序下载的文件完全是空白的,但是如果我在 PHP 代码之后写了一些东西,它就会写在我的文件上。我认为问题出在输入中,因为当我对此进行记录时,返回的值为 -1。

标签: java php android webview


【解决方案1】:

在您的代码中,您使用的是ob_clean(),它只会擦除输出缓冲区。因此,您随后对 flush() 的调用不会返回任何内容,因为输出缓冲区已预先刷新。

请使用ob_end_flush(),而不是ob_clean()flush()。这将停止输出缓冲,并将发送它保留的所有输出。

ob_end_flush — 刷新(发送)输出缓冲区并关闭输出缓冲

如果您想停止输出缓冲而不输出保存的任何内容,您可以使用ob_end_clean()。此命令之后的任何内容都将再次输出,但ob_start()ob_end_clean() 之间的任何内容都将被“吞下”。

ob_end_clean — 清理(擦除)输出缓冲区并关闭输出缓冲

首先,输出缓冲有什么好处?如果你在做ob_start(),然后在所有内容上使用flush(),你不妨直接输出所有内容。

【讨论】:

  • 感谢您的回答。我已经阅读了您的解决方案,我认为比我的更好,所以我已经更换了。但是我还无法获取文件。我尝试在 PHP 文件中添加 header("Content-Length: ".$file['size']) 并在 Java 中添加 int length = connection.getContentLength();文件和长度值为0。可能是BufferedInputStream的问题?
  • @AngelF。最好是从小处着手。我建议忘记输出缓冲区和设置标头,只阅读文件而不用太多。然后你可以逐步添加参数,例如内容的长度。
  • 我会去做的。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 2014-03-18
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多