2014-11-03 61 views
1

我有沒有辦法處理blob(保存到mysql的文件)而不必創建文件?PHP在不創建文件的情況下處理blob

我需要從數據庫中檢索一個blob,它可以是任何類型的文件,img,文本,視頻等,並且能夠在html中顯示它。

到目前爲止,我設法做的是創建一個文件並使用它。但是這有一個小問題,那就是我必須在用戶停止使用該文件後將其刪除。但是我不能在一段時間後創建一個cronjob(或者simillar)來刪除這些文件。

任何想法?

謝謝!

+0

是,不要創建文件。獲取你的mysql字段的內容,並將適當的頭添加到你的php中,並回應你的BLOB的內容。例如一個PNG圖像:'header('Content-Length:'.strlen($ data)); header(「Content-type:image/png」); echo $ data;' – vaso123 2014-11-03 14:11:41

回答

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"; 
} 
+0

嗨,謝謝你的回答。從blob中讀取內容類型是否可行?它應該在第一口,應該不是嗎? – leojg 2014-11-03 14:18:13

+0

這不太可能。你有一些函數存在這個purpouse:http://stackoverflow.com/questions/5304503/determinate-mime-type-from-mysql-column – dynamic 2014-11-03 14:24:35

+0

非常感謝,我會嘗試! – leojg 2014-11-03 14:37:07

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 peseudocode會是什麼樣子:

header('Content-Type: ' . get_blob_content_type($id), true); 
echo get_blob($id); 

get_blob_content_type()回報像image/jpgget_blob()返回的實際內容。

獎勵概念:如果您的blob具有關聯的文件名(例如,您將blob與其原始文件名一起存儲,例如cat.jpg),則可以將其指定給瀏覽器,因此如果用戶右鍵單擊並選擇保存,他們將獲得原始文件名稱。所有您需要做的是echo語句之前添加以下代碼:

header('Content-Disposition: inline; filename="' . get_blob_file_name($id) ."'); 

(確保你沒有報價在您的文件名!)

相關問題