我有办法处理blob(保存到mysql的文件)而不必创建文件吗?
我需要从数据库中检索一个blob,它可以是任何类型的文件,img,文本,视频等,并且能够以html显示它。
到目前为止,我设法做的是创建一个文件并使用它。但这有一点问题,我必须在用户停止使用该文件后删除它。但是我不能在一段时间后创建一个cronjob(或类似的东西)来删除这些文件。
任何想法?
谢谢!
答案 0 :(得分:2)
您可以拥有一个脚本,可以从数据库中即时打印文件的内容。 您所要做的就是存储其内容类型并从数据库中检索内容。
#showFile.php
$contenttype = ... // retrive content type from database
$blob = ... // retrive blob from database
header('Content-type: ' . $contenttype);
echo $blob;
如果您没有在数据库中保存MIME类型,可以尝试以下操作:Determinate mime type from MySQL column
function mimetype($data)
{
//File signatures with their associated mime type
$Types = array(
"474946383761"=>"image/gif", //GIF87a type gif
"474946383961"=>"image/gif", //GIF89a type gif
"89504E470D0A1A0A"=>"image/png",
"FFD8FFE0"=>"image/jpeg", //JFIF jpeg
"FFD8FFE1"=>"image/jpeg", //EXIF jpeg
"FFD8FFE8"=>"image/jpeg", //SPIFF jpeg
"25504446"=>"application/pdf",
"377ABCAF271C"=>"application/zip", //7-Zip zip file
"504B0304"=>"application/zip", //PK Zip file ( could also match other file types like docx, jar, etc )
);
$Signature = substr($data,0,60); //get first 60 bytes shouldnt need more then that to determine signature
$Signature = array_shift(unpack("H*",$Signature)); //String representation of the hex values
foreach($Types as $MagicNumber => $Mime)
{
if( stripos($Signature,$MagicNumber) === 0 )
return $Mime;
}
//Return octet-stream (binary content type) if no signature is found
return "application/octet-stream";
}
答案 1 :(得分:0)
显示存储在数据库中的内容的一种简单方法是创建另一个PHP脚本,比如show_content.php。
您可以在HTML中执行以下操作:
<img src="show_content.php?id=444" />
这将使用$_GET['id'] === '444'
在脚本中,假设您有一个名为get_blob($id)
和get_blob_content_type($id)
的函数。 show_content.php中的伪代码如下所示:
header('Content-Type: ' . get_blob_content_type($id), true);
echo get_blob($id);
get_blob_content_type()
返回image/jpg
之类的内容,而get_blob()
会返回实际内容。
奖励概念:如果您的blob具有关联的文件名(例如,您将blob与其原始文件名一起存储,例如cat.jpg
),则可以将其指定给浏览器,因此如果用户右键单击并且选择保存,他们将获得原始文件名。您所要做的就是在echo
语句之前添加以下代码:
header('Content-Disposition: inline; filename="' . get_blob_file_name($id) ."');
(请确保您的文件名中没有引号!)