簡體   English   中英

如何使用php腳本將圖像上傳到數據庫?

[英]How to upload an image to a database using php script?

這是我上載的代碼..但是它不起作用..我使用了file_get_contents函數。

</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”的數據庫和一個表

在數據庫中存儲圖像是一個壞主意。 將其路徑存儲在數據庫中,通過.htaccess關閉包含圖像的目錄,然后在硬盤上使用它。


為什么不應該在DB中存儲文件?

如果您將使用DB存儲圖像,則將具有:

  1. 慢查詢
  2. 災難性指標的大小
  3. 橋php <-> mysql上的高負載
  4. 編輯照片的問題(您需要獲取圖像,進行一些修改並再次插入所有數據。哦,不了)
  5. 文件從一個地方轉移到另一個地方的問題
  6. 關於StackOverflow的新問題«如果文件不是文件而是字符串,如何使用文件»

您應該在上傳過程中將文件保存在某個文件夾中,並將文件名保存在數據庫中,以便稍后可以從數據庫中調用文件名並將其鏈接為要下載的超鏈接,我正在使用以下代碼上傳圖像在名為files的文件夾中,並將文件名保存在數據庫中。 最后,我在變量$ 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>";
    }
}

將圖像直接上傳到數據庫不是一個好主意。 而是將照片上傳到文件夾中,然后僅將照片名稱插入數據庫中,然后在以后需要時調用它。 您可以根據需要嘗試以下代碼。

為了使代碼適合您,您必須執行以下步驟:

  1. 在代碼內部將“ your_photo”替換為您的輸入名稱(這種情況我想是“ image”)

  2. 創建一個要在其中上傳圖像的文件夾,然后在->> $ newname =“ support / images / profile /”中進行更改,在此處寫下您的圖像文件夾名稱

  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" />

首先檢查您是否確實能夠成功將文件上傳到服務器。 遵循本教程:

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

這將幫助您排除整個旅程的一半,但我強烈建議您檢查日志中是否存在實際錯誤,如果需要其他幫助,請明確指出它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM