2012-04-10 66 views
0

出於安全原因,我在MYSQL中存儲了一些圖片。當我下載圖像時,文件將以正確的文件大小和名稱下載,但不會顯示圖像。當我看着它的屬性時,圖像也沒有尺寸。我正在使用cakephp。下載時沒有尺寸的Mysql blob圖片

header("Content-type: ".$file['UploadFile']['file_extension']); 
header("Content-Disposition: attachment; filename=\"".$file['UploadFile']['file_name']."\""); 
header("Content-length: ".$file['UploadFile']['file_size']); 



echo $file['UploadFile']['file_content']; 

保存我的形象用下面的代碼...

public function image_upload($fileName, $source, $extension, $file_size) { 
    $this->loadModel('UploadFile'); 

    $content = addslashes(file_get_contents($source)); 

    $file_data = array('UploadFile' => array('title' => $fileName, 'file_content' => $content, 'file_name' => $fileName, 'file_extension' => $extension, 'file_size' => $file_size, 'file_type' => 'image-art')); 

    $this->UploadFile->create(); 
    $this->UploadFile->save($file_data); 

    $file_id = $this->UploadFile->id; 
    return $file_id; 
    } 
+0

打印'$文件[ 'UploadFile'] ['file_extension']'out,它返回什麼? – Dion 2012-04-10 21:16:13

+0

你的問題提出了兩個不同的概念 - 從數據庫中提取圖像 - 並從文件上傳中拉取圖像。你在說什麼? – Xeoncross 2012-04-10 21:26:54

+0

對不起,我在mysql中的表名是upload_files,所以對於cakephp你訪問數組中的數據與模型UploadFile – 2012-04-10 23:28:39

回答

4

他們是你可能有這樣

A.錯誤的內容類型幾個可能的原因..你有Content-type: ".$file['UploadFile']['file_extension']。 。在你的代碼中,這是worng`

例如。文件extention形成是財產以後像「.JPG」,而內容類型是image/jpeg

B.您的文件可能無法正確保存其中必須有導致

C.文件必須被截斷這種圖像上的腐敗上傳

D. $content = addslashes(file_get_contents($source));期間..永遠不要addslashes將圖像..它會messthing向上或準備好stripslashes當你加載圖像

要知道,如果你的形象是有效的,你下載你面前可以運行這個代碼

$image = ImageCreateFromString($file['UploadFile']['file_content']); 
if(!$image) 
    Something is Wrong 

您還可以使用getimagesize添加額外的驗證

編輯1

證明概念試試

$image = ImageCreateFromString ($file ['UploadFile'] ['file_content']); 
if ($image) { 

    /** 
    * Check If Height and Width is grater than 1 
    */ 
    if (ImageSX ($image) > 1 && ImageSY ($image) > 1) { 
     $extention = strtolower ($file ['UploadFile'] ['file_extension']); 
     switch ($extention) { 
      case "png" : 
       header ('Content-Type: image/png'); // This is just example 
       imagepng ($image); 
       break; 

      case "gif" : 
       header ('Content-Type: image/gif'); // This is just example 
       imagegif ($image); 
       break; 

      case "jpg" : 
      case "jpeg" : 
       header ('Content-Type: image/jpg'); // This is just example 
       imagejpeg ($image); 
       break; 

      default : 
       die ("Unsupported Image"); 
       break; 

     } 

    } else { 
     die ("Fake Image"); 
    } 
} else { 
    die ("Invalid Image -- Contains Errors"); 
}} 
+0

A.)我的file_extension實際上是mime類型,我需要更改數據庫中的字段名稱。 B.)我添加了我的代碼以保存上面的文件。 C.)我正在使用longblob,所以我不確定它是如何被截斷的,並且下載的文件完全是空白的,沒有排除 – 2012-04-10 23:36:10

+0

A)圖像在添加它們之後是否具有有效大小? B)'$ content = addslashes(file_get_contents($ source));'不要向圖像添加斜槓.....它會把它搞亂... – Baba 2012-04-11 00:10:21

+0

它似乎是add_slashes,我需要添加更多字段中的字符定義 – 2012-04-12 17:36:26