2012-01-04 180 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>"; 
    } 
} 
相关问题