使用Android Webview下载文件


Download files with Android Webview

我正在制作一个使用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;
}

日志。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文件,此文本写入文件下载。

在您的代码中,您使用的是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(),你也可以直接输出所有的东西。