【发布时间】:2017-11-27 16:53:41
【问题描述】:
当我从数据库下载 blob 图像时,其大小为 1 KB。当我打开 .png 文件本身时,图像没有出现。图像大小出现在我的 MySQL 数据库表中。我不明白为什么它会从我的数据库中下载一个空文件,而名称和文件类型却正确显示。
我的表格列
名称、文件类型和大小似乎一切都正确。
文件上传.php
<?php
require('config.php');
session_start();
if(isset($_POST['save']))
{
$target_dir = "upload/img/";
$filename = explode('.', $_FILES['image']['name']);
$ext = $filename[1];
$imgname = time() . '.' . $ext;
$target_file = $target_dir . $imgname;
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
$text = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$text = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if(file_exists($target_file)) {
$text = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if($_FILES["image"]["size"] > 2000000) {
$text = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" &&
$imageFileType != "gif" && $imageFileType != "bmp" ) {
echo "Sorry, only JPG, JPEG, PNG, GIF & BMP files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if($uploadOk == 0) {
$_SESSION["error"] = $text;
header("Location:index.php?id=$id"); /* Redirect browser */
exit();
// If everything is OK, try to upload the file
}else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
$path = $imgname;
$finfo = new finfo();
$array = explode('.', $_FILES['image']['name']);
$extension = end($array);
$filesize = $_FILES["image"]["size"];
$conn->query("INSERT INTO images (image,name,filetype,size) VALUES ('$path','$path','$extension','$filesize')");
$_SESSION["Success"] = 'Upload success';
header("Location:index.php"); /* Redirect browser */
exit();
} else {
$_SESSION["err"] = $text;
header("Location:index.php"); /* Redirect browser */
exit();
}
}
}
?>
文件下载.php
<?php
// Include configuration file
require_once 'config.php';
$id = $_GET["id"];
$sql = "select * from images where id=$id "; // 1
$res = $conn->query($sql);
while($row = $res->fetch_assoc())
{
$image = $row['image'];
$name = $row['name'];
$type = $row['filetype'];
$size = $row['size'];
}
header("Content-type: " . $type);
header('Content-Disposition: attachment; filename="' . $name . '"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: " . $size);
echo $image;
exit();
?>
【问题讨论】:
-
$path本质上是time().'.'.$ext;这是一个路径(因此是 14 字节)为什么你将它存储为 blob? -
$image基本上是文件的名称(这就是您存储在image字段中的内容)。您需要从使用路径保存文件的文件系统中读取文件并将其内容发送到客户端。此外,您的内容类型不准确,您需要获取正确的 mime 类型,而不仅仅是扩展名。我认为您将上传和下载 php 代码从您下载它们的任何地方混淆了。上传代码用于将数据保存到文件系统并链接到文件系统,而下载代码用于从数据库中获取图像数据。 -
用于定位PHP错误日志,规范为Where does PHP store the error log? (PHP 5, Apache, FastCGI, and cPanel)(尽管标题过于具体)。