2012-01-04 82 views
1

這裏是我上傳的代碼..但它不工作。我已經使用了的file_get_contents功能.. 上傳圖像如何使用php腳本將圖像上傳到數據庫?

</head> 
<body> 
    <form action="upload1.php" method="POST" enctype="multipart/form-data"> 
    File: 
    <input type="file" name="image"/> 
    <input type="submit" value="Upload image" /> 

    </form> 

<?php 

//connect to the database 
$con = mysql_connect("localhost","root", ""); 
if(!$con) 
{ 
die('Could not connect to the database:' . mysql_error()); 
echo "ERROR IN CONNECTION"; 
} 

mysql_select_db("imagedatabase", $con); 


//file properties 

echo $file = $_FILES['image']['tmp_name']; 
echo '<br />'; 

if(!isset($file)) 
echo "Please select an image"; 

else 
{ 
$image = file_get_contents($_FILES['image']['tmp_name']); 
echo $image_name = addslashes($_FILES['image']['name']); echo '<br \>'; 
echo $image_size = getimagesize($_FILES['image']['tmp_name']); 

if($image_size == FALSE) 
    echo "That's not an image"; 
    else 
{ 
     $insert = mysql_query("INSERT INTO images (image) VALUES ($image)",$con); 
if(!$insert) 
    echo "Problem uploding the image. Please check your database"; 
else 
{ 
    $last_id = mysql_insert_id(); 
    echo "Image Uploaded. <p /> Your image: <p /><img src=display.php?  id=$last_id>"; 
    } 
} 

} 
mysql_close($con); 
?> 

</body> 
</html> 

和檢索/顯示的代碼放在這方式..

<?php 
//connect to the database 
mysql_connect("localhost","root", "") or die(mysql_error()); 
mysql_select_db("mydb") or die(mysql_error()); 

//requesting image id 

$id = addslashes($_REQUEST['id']); 

$image = mysql_query("SELECT * FROM images WHERE id = $id"); 
$image = mysql_fetch_assoc($image); 
$image = $image['image']; 

header("Conten-type: image/jpeg"); 

echo $image; 


mysql_close($connect); 
?> 

我已經創建了一個名爲「imagedatabase」數據庫和表

+0

數據庫imagedatabase表爲圖像列裏面是ID -autoincrement,名字 - VARCHAR,圖像 - BLOB ..請幫助..即時通訊困惑 – SimonCode 2012-01-04 08:02:38

+0

這究竟是什麼不起作用?你有任何錯誤消息?更精確... – 2012-01-04 08:03:28

+1

已回答上: http://stackoverflow.com/questions/1636877/how-can-i-store-and-retrieve-images-from-a-mysql-database -using-php – 2012-01-04 08:05:30

回答

8

這是一個壞主意的圖像存儲在數據庫中。在數據庫中存儲路徑,通過.htaccess關閉包含圖像的目錄並將其用於硬盤​​。


爲什麼你不應該在DB中存儲文件?

如果您將使用DB來存儲圖像您將有:

  1. 慢查詢
  2. 災難性指標大小
  3. 上橋PHP <高負荷 - > mysql的
  4. 問題編輯照片(你需要得到圖像,修改一些東西 ,並再次插入所有數據。哦,哦)
  5. 傳輸文件從一個地方到在計算器上另一個
  6. 新問題«如何處理文件工作,如果他們不 文件,但字符串»
+0

即使查詢是正確的,圖像也不會上傳到數據庫。請幫忙。 – SimonCode 2012-01-04 08:08:39

+0

我想在使用硬盤驅動器服務器之前先使用數據庫。 – SimonCode 2012-01-04 08:11:50

+0

檢查您的$ _FILES ['image'] ['error']和表中的字段類型。也許你試圖在場上插入太多的數據,這可以接受一些小的東西?當您使用硬盤驅動器的數據庫時,將其設置爲BLOB – 2012-01-04 08:13:35

0

直接上傳圖片到數據庫不是一個好主意。而是將照片上傳到一個文件夾中,然後將照片名稱插入數據庫,然後在需要時再調用。如果你願意,你可以嘗試下面的代碼。

爲了使代碼對你的工作,你必須遵循以下步驟:

  1. 裏面的代碼與您輸入名稱替換「your_photo」(我猜這種情況下,這將是「圖像」)

  2. 創建一個文件夾,你會被上傳圖片,然後讓在變化 - >> $ NEWNAME =「支持/圖片/資料/」這裏寫你的圖片文件夾名

  3. 寫適當的數據庫查詢。並記住將自動創建圖像名稱,名稱保留在此變量 - > $ image_name中。將名稱插入數據庫時​​,只需使用$ image_name作爲值。

上傳腳本:

<? 
// If Everything is good- process the form - write the data into the database 

$photo=$this->input->post('your_photo'); 
if($photo==NULL){$image_name='0';}// if no photo is selected the default value of the photo would be 0 

    //photo upload starts 
     $errors=0; 
     if($_FILES['your_photo']){ 
     $image=$_FILES['your_photo']['name']; 
     if($image) { 
     define ("MAX_SIZE","100"); 
     function getExtension($str) { 
     $i = strrpos($str,"."); 
     if (!$i) { return ""; } 
     $l = strlen($str) - $i; 
     $ext = substr($str,$i+1,$l); 
     return $ext; } 


     //reads the name of the file the user submitted for uploading 
     $image=$_FILES['your_photo']['name'];         
     //if it is not empty 
     if ($image) 
     {        
     //get the original name of the file from the clients machine 
     $filename = stripslashes($_FILES['your_photo']['name']); 
     //get the extension of the file in a lower case format 
           $extension = getExtension($filename); 
           $extension = strtolower($extension); 
           //if it is not a known extension, we will suppose it is an error and will not upload the file, 
           //otherwise we will do more tests 
           if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
           {   
           //print error message 
           $msg="Sorry! Unknown extension. Please JPG,JPEG,PNG and GIF only "; 
           $errors=1; 

           } 
           else 
           { 
           //get the size of the image in bytes 
           //$_FILES['image']['tmp_name'] is the temporary filename of the file 
           //in which the uploaded file was stored on the server 
           $size=filesize($_FILES['your_photo']['tmp_name']);        
           //compare the size with the maxim size we defined and print error if bigger 
           if ($size < MAX_SIZE*1024) 
           { 
           //we will give an unique name, for example the time in unix time format 
           $image_name=time().'.'.$extension; 
           //the new name will be containing the full path where will be stored (images folder)               
           $newname="support/images/profile/".$image_name;              
           //we verify if the image has been uploaded, and print error instead              
           $copied = copy($_FILES['your_photo']['tmp_name'], $newname);               
           if (!$copied)              
           {              
           $msg="Sorry, The Photo Upload was unsuccessfull!";               
           $errors=1;               
           }               
           }            
           else            
           {  
           $msg="You Have Exceeded The Photo Size Limit";   
           $errors=1;        
           }           
           }}}            

           /*Image upload process ends here- If any problem occurs it will display error message via the $msg, 
           otherwise it will upload the image to the image folder. To insert the photo into database $image_name has been used*/ 

        } 


        if(($_FILES['your_photo'])&& ($errors))/* If any photo is selected and any problem occurs while uploading it will 
                   display an error message, otherwise transfer the data to Mod_addstudent model */ 
             { 

           echo $msg; 


             } 

        else  { 

            //Insert into database.Just use this particular variable "$image_name" when you are inserting into database 

             $sql="INSERT INTO your_table (field1, your_image_field) VALUES ('','$image_name')"; 




           } 
       ?> 

然後查看圖像::

<?php 

// Retrieve information from Database First and then .. 

if (empty($your_photo)) 

{ $image_location="images/avatar.jpg";} //if there is no image in database 

else {$image_location="images/$your_photo";} // if there is any image in database 

?> 



    <img src="<?php echo base_url(); ?><?php echo $image_location ;?>" width="150" height="170" /> 
+0

嘿@Srijon感謝代碼..我會嘗試這一個..我只是有一個確認,我們可以使用服務器作爲我們的圖像存儲。非常感謝..我們正在做我們的論文。: D – SimonCode 2012-01-04 10:46:04

+0

請原諒我,但是你給我的代碼不工作.. hehehe ..我跟着你告訴我的步驟,但是當表單進入upload.php時,它顯示了整個代碼,爲什麼? – SimonCode 2012-01-05 15:42:22

+0

there這是一個錯誤..這裏.. 致命錯誤:使用$這不當在對象上下文在C:\ XAMP \ xampp \ htdocs \ gallery \ gallerysamp.php在線4 – SimonCode 2012-01-05 15:44:08

0

檢查你居然能到一個文件中第一次成功上傳到你的服務器。按照本教程:

http://www.tizag.com/phpT/fileupload.php

這將幫助您解決您的旅程的一半,但我強烈建議你檢查你的日誌的實際錯誤,如果你想要更多的幫助你明確他們。

1

你應該在上傳過程中的文件保存在某個文件夾,並保存在數據庫文件的名稱,這樣以後就可以從數據庫調用文件的名稱,我使用它鏈接的鏈接下載以下代碼將圖像上傳到稱爲文件的文件夾中,並將文件的名稱保存在數據庫中。最後我有變量$ NEWNAME的文件名

if ($_FILES['file']['name']) { 

    $allowedExts = array("gif", "jpeg", "jpg", "png"); 
    $temp = explode(".", $_FILES["file"]["name"]); 
    $extension = end($temp); 
    if ((($_FILES["file"]["type"] == "image/gif") 
      || ($_FILES["file"]["type"] == "image/jpeg") 
      || ($_FILES["file"]["type"] == "image/jpg") 
      || ($_FILES["file"]["type"] == "image/pjpeg") 
      || ($_FILES["file"]["type"] == "image/x-png") 
      || ($_FILES["file"]["type"] == "image/png")) 
     && ($_FILES["file"]["size"] < 500000) 
     && in_array($extension, $allowedExts) 
    ) { 
     if ($_FILES["file"]["error"] > 0) { 
      echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; 
     } else { 
      $ext = end(explode(".", $_FILES["file"]["name"])); 
      $filename = current(explode(".", $_FILES["file"]["name"])); 
      $newname = $filename . '_' . time() . '.' . $ext; 
      move_uploaded_file($_FILES["file"]["tmp_name"], 
       "files/" . $newname); 
     } 
    } else { 
     echo "<div class='alert alert-success'>Image type or size is not valid.</div>"; 
    } 
} 
相關問題