php - 如何在数据库中插入图片?

时间:2016-11-10 15:29:46

标签: php

到目前为止,我可以在我的文件夹路径中上传图片,但我不知道如何将其存储在数据库中。我试过几个例子但到目前为止没有运气。任何人都可以帮助我吗?

upload.php的

<?php
//turn on php error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $name     = $_FILES['file']['name'];
    $tmpName  = $_FILES['file']['tmp_name'];
    $error    = $_FILES['file']['error'];
    $size     = $_FILES['file']['size'];
    $ext      = strtolower(pathinfo($name, PATHINFO_EXTENSION));

    switch ($error) {
        case UPLOAD_ERR_OK:
            $valid = true;
            //validate file extensions
            if ( !in_array($ext, array('jpg','jpeg','png','gif')) ) {
                $valid = false;
                $response = 'Invalid file extension.';
            }
            //validate file size
            if ( $size/1024/1024 > 2 ) {
                $valid = false;
                $response = 'File size is exceeding maximum allowed size.';
            }
            //upload file
            if ($valid) {
                $targetPath =  dirname( __FILE__ ) . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR. $name;
                move_uploaded_file($tmpName,$targetPath); 
                header( 'Location: index.php' ) ;
                exit;
            }
            break;
        case UPLOAD_ERR_INI_SIZE:
            $response = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
            break;
        case UPLOAD_ERR_PARTIAL:
            $response = 'The uploaded file was only partially uploaded.';
            break;
        case UPLOAD_ERR_NO_FILE:
            $response = 'No file was uploaded.';
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
            $response = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.';
            break;
        case UPLOAD_ERR_CANT_WRITE:
            $response = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
            break;
        default:
            $response = 'Unknown error';
        break;
    }

    echo $response;
}
?>

uploadPicture.php

<?php 
include_once("login_check.inc");
include_once("database/connection.inc");

?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>PHP File Uploader</title>

    <!-- Bootstrap core CSS -->
    <link href="boostrap/css/bootstrap.min.css" rel="stylesheet">

  </head>

  <body>

    <!-- Static navbar -->
    <div class="navbar navbar-default navbar-static-top">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="index.php">PHP File Uploader</a>
        </div>
      </div>
    </div>


    <div class="container">

        <div class="row">
           <?php 
            //scan "uploads" folder and display them accordingly
           $folder = "uploads";
           $results = scandir('uploads');
           foreach ($results as $result) {
            if ($result === '.' or $result === '..') continue;

            if (is_file($folder . '/' . $result)) {
                echo '
                <div class="col-md-3">
                    <div class="thumbnail">
                        <img src="'.$folder . '/' . $result.'" alt="...">
                            <div class="caption">
                            <p><a href="remove.php?name='.$result.'" class="btn btn-danger btn-xs" role="button">Remove</a></p>
                        </div>
                    </div>
                </div>';
            }
           }
           ?>
        </div>

          <div class="row">
            <div class="col-lg-12">
               <form class="well" action="upload.php" method="post" enctype="multipart/form-data">
                  <div class="form-group">
                    <label for="file">Select a file to upload</label>
                    <input type="file" name="file">
                    <p class="help-block">Only jpg,jpeg,png and gif file with maximum size of 1 MB is allowed.</p>
                  </div>
                  <input type="submit" class="btn btn-lg btn-primary" value="Upload">
                </form>
            </div>
          </div>

    </div> <!-- /container -->

  </body>
</html>

http://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html

2 个答案:

答案 0 :(得分:0)

您可以通过多种方式将图像保存到数据库中。我倾向于base64编码图像并保存扩展名。我不知道这是否是最实用的方法。

// Encoding the image
$images = file_get_cntents('image.jpg');
$encodedImage = base64_encode($image);

答案 1 :(得分:0)

我会质疑在数据库中存储图像的愿望。一般来说,在关系数据库中存储二进制文件有点像反模式。这样做的主要用例可能是你需要对文件的二进制内容执行二进制搜索,这是一个稀有用例。

除此之外,将文件放入数据库通常会带来以下问题:

  • 这使得对资产进行适当的浏览器端缓存变得更加困难。
  • 它使您的应用程序对提供这些文件的带宽密集程度更高。为什么要让应用程序从数据库中检索文件,然后才能将其提供给请求客户端?这使向最终用户提供此文件所需的带宽加倍,因为应用程序首先需要检索二进制文件然后转向并将该二进制文件提供给最终客户端。这意味着您的应用程序对最终用户的感知要慢得多。通常情况下,最好只从DB获取文件路径引用,让最终客户端直接从Web可访问目录或其他存储机制(例如CDN)下载文件。
  • 随着文件数量的增长,它使维护数据库的问题更加严重。存储在表中的数据大小会非常快,从而影响可能对数据库执行的各种维护操作 - 备份,还原等。
  • 您失去了对文件进行操作的能力,因为人们通常期望使用文件集合。诸如海量文件移动/复制,修订控制等等现在成为您需要通过数据库接口完成的事情,在您的应用程序中引入了额外的复杂性。