gpt4 book ai didi

php - 为什么存储在 mysql 数据库中的 PDF 文件在下载时损坏/损坏?

转载 作者:可可西里 更新时间:2023-11-01 08:36:48 25 4
gpt4 key购买 nike

我正在创建用户可以上传/下载存储在 mysql 数据库中的 pdf 文件的页面,问题是当我下载文件时,它会损坏/损坏

NP:文件的数据在数据库中存储为blob。

下面是我的代码:

        // Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);

// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";

// Execute the query
$result = $dbLink->query($query);

// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}

// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}

download code:
// Fetch the file information
$query = "
SELECT `mime`, `name`, `size`, `data`
FROM `file`
WHERE `id` = {$id}";
$result = $dbLink->query($query);

if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);

// Print headers
//header('Content-Type: application/pdf');
header("Content-Type: application/force-download");
header("Pragma: public");
header("Content-Description: File Transfer");
header("Content-Type: ".$row['mime']);
header("Content-Length: ".$row['size']);
header("Content-Disposition: attachment; filename=".$row['name']);
header("Content-Transfer-Encoding: binary");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
// Print data
@readfile($row['data']);
}
else {
echo 'Error! No file exists with that ID.';
}

// Free the mysqli resources
@mysqli_free_result($result);
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
@mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}

最佳答案

不是这样。 Mysqli 也不是这样。你总是有选择,告诉你的老师这种方法没有值(value)。为什么不将 jpg 存储在 mysql 数据库中?因为有更好的方法 - 将链接存储在数据库中,将 .jpg 存储在 Web 上。与 PDF 相同。如果您必须仔细阅读,请查看基于 Web 的编辑器(如 ckedit)如何存储数据(另一种错误方法。),并查看 dompdf code.google.com/p/dompdf/以了解是什么破坏了 pdf 格式。

为什么 mysqli 是个坏主意? mySql 就是这样。 mySql 试图使它成为用其他方法更好地完成的其他事情,否则 mysql 会这样做。

关于php - 为什么存储在 mysql 数据库中的 PDF 文件在下载时损坏/损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9713204/

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