簡體   English   中英

使用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;
}

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文件的“?>”之后寫一些文本,則此文本將寫在下載的文件中。

在您的代碼中,您使用的是ob_clean() ,這只會刪除輸出緩沖區。 因此,您隨后對flush()調用不會返回任何內容,因為輸出緩沖區已預先刷新。

代替ob_clean()flush() ,使用ob_end_flush() 這將停止輸出緩沖,並將發送所有保留的輸出。

ob_end_flush —刷新(發送)輸出緩沖區並關閉輸出緩沖

如果要停止輸出輸出緩沖而不輸出任何已保存的內容,則可以使用ob_end_clean() 此命令之后的所有內容都會再次輸出,但是ob_start()ob_end_clean()都會被“吞咽”。

ob_end_clean —清理(擦除)輸出緩沖區並關閉輸出緩沖

首先,輸出緩沖的好處是什么? 如果您正在執行ob_start() ,然后對所有內容都使用flush() ,則不妨直接輸出所有內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM