gpt4 book ai didi

php - header 下载文件已损坏

转载 作者:可可西里 更新时间:2023-11-01 13:01:06 27 4
gpt4 key购买 nike

我正在尝试通过我的数据库中的 header 下载文件。我不确定为什么当我将下载代码更改为使用 OOP 的代码时我下载的文件都已损坏,但当我的代码不是 OOP 时却没问题。

这是我获取文件 ID 并调用下载函数的地方:(handleDownload.php)

if (isset($_GET['id'])) {
$id = $_GET['id'];
//pump id into function getDBFiles to pull file with matching id
$fileData = $Download->getDBFiles($id);
header('Content-Type:"' . $fileData[2]. '"');
header('Content-Disposition: attachment; filename="' . $fileData[1]. '"');
echo $fileData[0];
exit;
}

这是从数据库(download.php)中提取文件的函数

public function getDBFiles($id) {
global $database;
$sql = "SELECT * FROM ".self::$table_name." WHERE resume_id ='" . $id . "'";
$result = $database->query($sql);
if ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$name = $row['resume_title'];
$type = $row['file_type'];
$content = $row['resume_data']; //content of file
//$size = $row['file_size']; //file size
return array($content, $name, $type);
}
}
$Download = new Download();
$download =& $Download;

如果代码全部在一个页面中,则代码工作正常,如下所示:

if (isset($_GET['id'])) {
$id = $_GET['id'];
mysqli_select_db($con, "apples");

$query = "SELECT * FROM resume where resume_id ='" . $id . "'";
$result = mysqli_query($con, $query) or die('Error, query failed');


if ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$name = $row['resume_title'];
$type = $row['file_type'];
$content = $row['resume_data']; //content of file
$size = $row['file_size']; //file size
header('Content-Type:"' . $type . '"');
//header('Content-length:"' . $size . '"');
header('Content-Disposition: attachment; filename="' . $name . '"');
//var_dump($row);
echo $content;
}
}

更新:我现在得到的下载文件已损坏,而不是空白文件。这就是同一个文件被不同的下载代码输出的方式。最上面的一个来自 OOP 代码,而另一个来自工作的非 OOP 版本。 hex comparison

这是我的完整下载代码。

try {
//execute retrieval of files from database
$Download-> showDBFiles();
//pass results to output array
$output = $Download->getMessages();
//if id is set then get file from database
if (isset($_GET['id'])) {
$id = $_GET['id'];
//pump id into function getDBFiles to pull file with matching id
$fileData = $Download->getDBFiles($id);
header('Content-Type:"' . $fileData[2]. '"');
header('Content-Disposition: attachment; filename="' . $fileData[1]. '"');
echo $fileData[0];
die();
}
} catch (Exception $e) {
$result[] = $e->getMessages();
}

调用函数后,我会用 foreach 循环回显输出(下载链接)

<h2>Output</h2>
<?php if ($output) { ?>
<ul class="result">
<?php
foreach ($output as $message) {
$id = $message['id'];
$name = $message['name'];
?>
<li><a href="handleDownload.php?id=<?php echo $id; ?>"><?php echo $name; ?></a></li>

<?php }
?>
</ul>

最佳答案

在您的非 OOP 解决方案中,检查 php 文件中的前导空格。

由于前导空格,以下代码会生成损坏的文件。

 <?php
if (isset($_GET['id'])) {...

这也适用于结束 php 标记后的空格(您不应使用)。

这些字符将由您的浏览器提交,包含在下载流中并损坏整个文件。

关于php - header 下载文件已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31770491/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com