【发布时间】: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。