Как загрузить изображение в базу данных, используя скрипт php? - PullRequest
1 голос
/ 04 января 2012

вот код для моей загрузки .. но он не работает .. Я использовал функцию 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' и таблицу

Ответы [ 4 ]

8 голосов
/ 04 января 2012

Плохая идея хранить изображение в базе данных. Сохраните путь к нему в базе данных, закройте каталог с изображениями через .htaccess и используйте его на жестком диске.


Почему Вы не должны хранить файлы в БД?

Если вы будете использовать БД для хранения изображений, у вас будет:

  1. медленные запросы
  2. размер катастрофических индексов
  3. высокая нагрузка на мост php <-> mysql
  4. проблемы с редактированием фотографий (Вам нужно получить изображение, изменить что-то и вставьте все данные снова. Оооооо)
  5. проблемы с переносом файлов из одного места в другое
  6. новый вопрос по StackOverflow «Как работать с файлами, если их нет файлы, но строка »
1 голос
/ 08 марта 2014

Вы должны сохранить файлы в какой-то папке во время процесса загрузки и сохранить имя файла в базе данных, чтобы позже вы могли вызвать имя файла из базы данных и связать его как гиперссылку для загрузки, я использую следующий кодзагружать изображения в папку с именем 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>";
    }
}
0 голосов
/ 04 января 2012

Убедитесь, что вы действительно можете сначала успешно загрузить файл на свой сервер.Следуйте этому руководству:

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

Это поможет вам устранить неполадки в половине вашего путешествия, но я настоятельно рекомендую вам проверить ваши журналы на наличие реальных ошибок и, если вам нужна дополнительная помощь, вы явноих.

0 голосов
/ 04 января 2012

Загрузка изображений непосредственно в базу данных не очень хорошая идея. Вместо этого загрузите фотографии в папку, а затем просто вставьте имя фотографии в базу данных, а затем вызывайте ее позже, когда вам нужно. Вы можете попробовать следующий код, если хотите.

Чтобы код работал для вас, вам нужно выполнить следующие шаги:

  1. Внутри кода Замените «your_photo» на ваше имя (в этом случае я думаю, что это будет «изображение»)

  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" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...