简体   繁体   English

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

[英]php - How to insert picture in database?

So far i can upload a picture in my folder path, but i don't have an idea how can store that in Database. 到目前为止,我可以在文件夹路径中上传图片,但是我不知道如何将其存储在数据库中。 I have tried a couple of examples but no luck so far. 我已经尝试了几个例子,但到目前为止还没有运气。 Can anyone help me? 谁能帮我?

Upload.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 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>

这是我要在其中插入图片路径的数据库表

You can save images to the database in multiple ways. 您可以通过多种方式将图像保存到数据库。 I tend to base64 encode the image and save the extension. 我倾向于对图像进行base64编码并保存扩展名。 I don't know if this is the most practical method though. 我不知道这是否是最实用的方法。

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

I would question the desire to store images in the database to begin with. 我会质疑将图像存储在数据库中的愿望。 Generally speaking, storing binary files in a relational database is a bit of an anti-pattern. 一般而言,将二进制文件存储在关系数据库中有点反模式。 Probably the main use case for doing this is if you need to perform a binary search against the binary contents of the file, which is a rare use case. 这样做的主要用例可能是您需要对文件的二进制内容执行二进制搜索,这种情况很少见

Outside of that, putting files in database often poses the following problems: 除此之外,将文件放入数据库通常会带来以下问题:

  • It makes it more difficult to enable proper browser-side caching of the assets. 这使得对资产进行适当的浏览器端缓存变得更加困难。
  • It makes your application much more bandwidth intensive to serve up these files. 它使您的应用程序占用大量带宽,以提供这些文件。 Why make your application retrieve the file from a database before being able to then serve it up to requesting client? 为什么要让您的应用程序从数据库中检索文件,然后才能将其提供给请求的客户端? This doubles the bandwidth necessary to serve this file to the end user, as the application first needs to retrieve the binary and then turn around and serve up that binary to the end client. 这将为最终用户提供此文件所需的带宽增加了一倍,因为应用程序首先需要检索二进制文件,然后转过来再将该二进制文件提供给最终客户端。 This means your application is that much slower in the perception of your end user. 这意味着您的应用程序对最终用户的感知要慢得多。 Oftentimes, it is better just to get the file path reference from the DB and let the end client download files directly from web-accessible directory or other storage mechanisms (a CDN for example). 通常,最好只是从数据库中获取文件路径引用,并让最终客户端直接从可从Web访问的目录或其他存储机制(例如CDN)中下载文件。
  • It makes maintaining your database more problematic as number of files grows. 随着文件数量的增加,维护数据库变得更加困难。 The size of data stored in your tables can become very large very quickly, impacting the various maintenance operations one might perform against the database - backups, restores, etc. 表中存储的数据大小可能很快变得非常大,从而影响人们可能对数据库执行的各种维护操作-备份,还原等。
  • You lose the ability to operate against files as one would typically expect to work with a collection of files. 您将失去对文件进行操作的能力,就像通常希望处理一组文件一样。 Things such as mass file move/copies, revision control, etc. now become things you need to do via database interface, introducing additional complexity in your application. 现在,大量文件移动/复制,修订控制等工作已成为您需要通过数据库接口执行的操作,从而在应用程序中带来了额外的复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM