我已将一个pdf文件保存在mysql数据库中作为MEDIUMBLOB文件。我使用以下代码下载它。下载的文件与原始文件的大小和文件类型相同,但它无法正常打开。可能是什么问题&如何解决?
$emp_no=55;
$DOB="2014-09-03";
$query="SELECT file_name, file_type, file_size, file_data FROM document WHERE emp_no=$emp_no AND DOB='$DOB'";
$retval=mysqli_query($non,$query);
$row=mysqli_fetch_array($retval,MYSQL_ASSOC);
$file_name=$row['file_name'];
$file_type=$row['file_type'];
$file_size=$row['file_size'];
$file_data=$row['file_data'];
header("Content-length: $file_size");
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=$file_name");
echo $file_data;
答案 0 :(得分:1)
在记事本中打开你下载的.pdf,你会看到文件顶部有PHP错误通知,这些会破坏任何下载的文件。
一些解决方案:
error_reporting(E_ERROR);
关闭E_NOTICE错误报告ini_set('display_errors', 0);
关闭错误打印到浏览器,以免他们弄乱下载的文件您可以修复这些内容,也可以添加
答案 1 :(得分:0)
这是我最后的工作解决方案:
<?php
header ('Content-type: text/html; charset=UTF-8');
//Get id from form (POST)
$order = $_POST['Order'];
//Set connection
$servername = "mysql.yourserver.com";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabasename";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Error: " . $conn->connect_error);
}
//Retrieve data from db
$result = $conn->query('SELECT * FROM Table WHERE id='.$order);
//Set rows to variables
while($row = $result->fetch_assoc()) {
$size = $row["size"];
$type = $row["type"];
$filename = $row["filename"];
$content = $row["content"];
}
//Get file
header("Content-disposition: attachment; filename=$filename");
header("Content-length: $size");
header("Content-type: $type");
echo $content;
//End connection
$conn->close();
?>
&#13;