Nuke Olaf - Log Store

MySQL 에 BLOB으로 이미지 저장하기 본문

Language/[PHP]

MySQL 에 BLOB으로 이미지 저장하기

NukeOlaf 2020. 2. 11. 19:31

1. BLOB 란?

Binary Large Object 의 약어이다.

이진 데이터를 저장하기 위한 MySQL 의 필드 유형이라고 한다.

이미지의 경우 이진 데이터로 이루어져 있기 때문에 BLOB 유형의 데이터로 만들어서,
MySQL 데이터베이스에 저장할 수 있다.

MySQL 에는 4가지의 BLOB 타입이 있다.

  • BLOB
  • TINYBLOB
  • MEDIUMBLOB
  • LONGBLOB

 

2. 이미지를 저장할 테이블 만들기

CREATE TABLE testblob (
  image_id tinyint(3) NOT NULL AUTO_INCREMENT,
  image_type varchar(25) NOT NULL,
  image longblob NOT NULL,
  image_size varchar(255) NOT NULL,
  image_name varchar(50) NOT NULL,
  KEY image_id (image_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

3. 이미지 업로드 하기

여타 파일 업로드와 마찬가지로 form 태그를 이용하여 이미지를 업로드 한다.

upload-image.html

<!DOCTYPE html>

<html>
<head><title>File Upload To Database</title></head>
<body>
<h2>Please Choose a File and click Submit</h2>
<form enctype="multipart/form-data" action="uploadImage.php" method="post">
    <div><input name="userfile" type="file"/></div>
    <div><input type="submit" value="Submit"/></div>
</form>

</body>
</html>

 

upload-image.php

<?php
/*** check if a file was submitted ***/
if(!isset($_FILES['userfile']))
{
    echo '<p>Please select a file</p>';
}
else
{
    try    {
        upload();
        /*** give praise and thanks to the php gods ***/
        echo '<p>Thank you for submitting</p>';
    }
    catch(Exception $e)
    {
        echo '<h4>'.$e->getMessage().'</h4>';
    }
}

function upload(){
    /*** check if a file was uploaded ***/
    if(is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false)
    {
        /***  get the image info. ***/
        $size = getimagesize($_FILES['userfile']['tmp_name']);
        /*** assign our variables ***/
        $type = $size['mime'];
        $imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb');
        $size = $size[3];
        $name = $_FILES['userfile']['name'];
        $maxsize = 99999999;


        /***  check the file is less than the maximum file size ***/
        if($_FILES['userfile']['size'] < $maxsize )
        {
            /*** connect to db ***/
            $dbh = new PDO("mysql:host=127.0.0.1;dbname=test_db", 'root', 'root-password');

            /*** set the error mode ***/
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            /*** our sql query ***/
            $stmt = $dbh->prepare("INSERT INTO testblob (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");

            /*** bind the params ***/
            $stmt->bindParam(1, $type);
            $stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
            $stmt->bindParam(3, $size);
            $stmt->bindParam(4, $name);

            /*** execute the query ***/
            $stmt->execute();
        }
        else
        {
            /*** throw an exception is image is not of type ***/
            throw new Exception("File Size Error");
        }
    }
    else
    {
        // if the file is not less than the maximum allowed, print an error
        throw new Exception("Unsupported Image Format!");
    }
}
?>

 

4. 이미지 불러오기

show-file.php

<?php

/*** assign the image id ***/
$image_id = 3;
try     {
    /*** connect to the database ***/
    $dbh = new PDO("mysql:host=127.0.0.1;dbname=test_db", 'root', 'root-password');

    /*** set the PDO error mode to exception ***/
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    /*** The sql statement ***/
    $sql = "SELECT image, image_type FROM testblob WHERE image_id=$image_id";

    /*** prepare the sql ***/
    $stmt = $dbh->prepare($sql);

    /*** exceute the query ***/
    $stmt->execute();

    /*** set the fetch mode to associative array ***/
    $stmt->setFetchMode(PDO::FETCH_ASSOC);

    /*** set the header for the image ***/
    $array = $stmt->fetch();

    /*** check we have a single image and type ***/
    if(sizeof($array) == 2)
    {
        /*** set the headers and display the image ***/
        header("Content-type: ".$array['image_type']);

        /*** output the image ***/
        echo $array['image'];
    }
    else
    {
        throw new Exception("Out of bounds Error");
    }
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
catch(Exception $e)
{
    echo $e->getMessage();
}
?>

 

참고 사이트>>>

https://phpro.org/tutorials/Storing-Images-in-MySQL-with-PHP.html

https://heropy.blog/2019/02/28/blob/

https://stackoverflow.com/questions/6472233/can-i-store-images-in-mysql

Comments