【问题标题】:View Blob File Content查看 Blob 文件内容
【发布时间】:2011-12-14 02:33:44
【问题描述】:

使用我在“devarticles.com”和“mistonline”上找到的一些示例,我将下面显示的脚本放在一起,该脚本允许用户将图像文件保存到 mySQL 数据库,将文件保存为 BLOB。

<?php
$db_host = 'hostname'; 
$db_user = 'username';
$db_pwd = 'password';

$database = 'databasename';
$table = 'tablename';
// use the same name as SQL table


if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);

    return mysql_real_escape_string($s);
}

// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // cleaning title field
    $title = trim(sql_safe($_POST['title']));

    if ($title == '') // if title is not set
        $title = '(empty title)';// use (empty title) string

    {
        if (isset($_FILES['photo']))
        {
            @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
            // Get image type.
            // We use @ to omit errors

            if ($imtype == 3) // cheking image type
                $ext="png";   // to use it later in HTTP headers
            elseif ($imtype == 2)
                $ext="jpeg";
            elseif ($imtype == 1)
                $ext="gif";
            else
                $msg = 'Error: unknown file format';

            if (!isset($msg)) // If there was no error
            {
                $data = file_get_contents($_FILES['photo']['tmp_name']);
                $data = mysql_real_escape_string($data);
                // Preparing data to be used in MySQL query

                mysql_query("INSERT INTO {$table}
                                SET ext='$ext', title='$title',
                                    data='$data'");

                $msg = 'Success: image uploaded';
            }
        }
        elseif (isset($_GET['title']))      // isset(..title) needed
            $msg = 'Error: file not loaded';// to make sure we've using
                                            // upload form, not form
                                            // for deletion

                if (isset($_POST['del'])) // If used selected some photo to delete
        {                         // in 'uploaded images form';
            $imageid = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
            $msg = 'Photo deleted';
        }
        if (isset($_POST['view'])) // If used selected some photo to delete 
{ // in 'uploaded images form'; 
$imageid = intval($_POST['view']); 
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid"); 
if(mysql_num_rows($result) == 1) 
{ 
$image = $row['myimage']; 
header("Content-type: image/gif"); // or whatever 
print $image; 
exit; 
} 
} 


    }
}
elseif (isset($_GET['show']))
{
    $imageid = intval($_GET['show']);

    $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
                             FROM {$table}
                            WHERE imageid=$imageid LIMIT 1");

    if (mysql_num_rows($result) == 0)
        die('no image');

    list($ext, $imagetime, $data) = mysql_fetch_row($result);

    $send_304 = false;
    if (php_sapi_name() == 'apache') {
        // if our web server is apache
        // we get check HTTP
        // If-Modified-Since header
        // and do not send image
        // if there is a cached version

        $ar = apache_request_headers();
        if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
            ($ar['If-Modified-Since'] != '') && // not empty
            (strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
            $send_304 = true;                                     // imagetime
    }

    if ($send_304)
    {
        // Sending 304 response to browser
        // "Browser, your cached version of image is OK
        // we're not sending anything new to you"
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);

        exit(); // bye-bye
    }

    // outputing HTTP headers
    header('Content-Length: '.strlen($data));
    header("Content-type: image/{$ext}");

    // outputing image
    echo $data;
    exit();
}
?>
<html><head>
<title>Save Photo(s) to Find</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for
                 // outputing message
{
?>
<p style="font-weight: bold;"><?=$msg?>
<br />
</p>
<?php
}
?>
<h1>Save Find images </h1>
<h2>Uploaded Find images:</h2>
<form action="<?=$PHP_SELF?>" method="post">
<!-- This form is used for image deletion -->

<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
    echo '<ul><li>No images loaded</li></ul>';
else
{
    echo '<ul>';
    while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
    {
        // outputing list
        echo "<li><input type='radio' name='del' title, value='{$imageid}'/>";
        echo "&nbsp;<small>{$title}</small>&nbsp;&nbsp";
        echo "<small>{$imagetime}</small></li>";
    }

    echo '</ul>';

    echo '<input type="submit" value="Delete selected"/>';

    echo "<input type=\"button\" value=\"View Photo\" onclick=\"location.href='<?=$PHP_SELF?>?show=1'\" />"; 
}
?>

</form>
<h2>Upload new Find image:</h2>
<form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
<label for="title"></label>
<label for="photo"></label>
<label for="password"></label>
<table border="0" cellpadding="0" cellspacing="0" bordercolor="#111111" width="38%">
  <tr>
    <td bgcolor="#FF9900" height="22" colspan="2"><p style="margin-left: 10"><b><font face="Verdana" size="2" color="#FFFFFF"> Upload a File</font></b></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB" colspan="2"><p style="margin-left: 10; margin-right: 10"><font face="Verdana" size="2"> <br>
      Please select a file from your local computer to upload to our web server 

      for saving in our database. This file can be of any type you like. Once you 

      have chosen a file, please click on the &quot;Upload this file&quot; button below.&nbsp;

      &nbsp;<br>
      &nbsp;</font></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> File Description:</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input type="text" name="title" id="title" size="64"/></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB"><span style="margin-left: 10"><font face="Verdana" size="2">File Location:</font></span></td>
    <td bgcolor="#FFE3BB"><input type="file" name="photo" id="photo"/></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> <br>
              <br>
      &nbsp;</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input name="submit" type="submit" value="Upload This File"/></td>
  </tr>
</table>
<p>&nbsp;</p>
<p>&nbsp;</p>
</form>
</body>
</html>

我可以保存、列出保存的文件并从数据库中删除文件,但我遇到了一个问题,即我不知道如何检索和查看图像,实际上我的“查看照片”已删除它。

我认为答案在“输出列表”部分,但我已经尝试了各种方法来尝试“查看照片”按钮来执行“查看”命令。

我只是想知道是否有人可以看看这个并让我知道我哪里出错了。

【问题讨论】:

    标签: php blob


    【解决方案1】:

    这里是:

    <?php
    $db_host = 'localhost'; 
    $db_user = '';
    $db_pwd = '';
    
    $database = '';
    $table = 'images';
    // use the same name as SQL table
    
    if (!mysql_connect($db_host, $db_user, $db_pwd))
        die("Can't connect to database");
    
    if (!mysql_select_db($database))
        die("Can't select database");
    
    // This function makes usage of
    // $_GET, $_POST, etc... variables
    // completly safe in SQL queries
    function sql_safe($s)
    {
        if (get_magic_quotes_gpc())
            $s = stripslashes($s);
    
        return mysql_real_escape_string($s);
    }
    
    // If user pressed submit in one of the forms
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if (!isset($_POST["action"]))
        {
            // cleaning title field
            $title = trim(sql_safe($_POST['title']));
    
            if ($title == '') // if title is not set
                $title = '(empty title)';// use (empty title) string
    
            if (isset($_FILES['photo']))
            {
                @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
                // Get image type.
                // We use @ to omit errors
    
                if ($imtype == 3) // cheking image type
                    $ext="png";   // to use it later in HTTP headers
                elseif ($imtype == 2)
                    $ext="jpeg";
                elseif ($imtype == 1)
                    $ext="gif";
                else
                    $msg = 'Error: unknown file format';
    
                if (!isset($msg)) // If there was no error
                {
                    $data = file_get_contents($_FILES['photo']['tmp_name']);
                    $data = mysql_real_escape_string($data);
                    // Preparing data to be used in MySQL query
    
                    mysql_query("INSERT INTO {$table}
                                    SET ext='$ext', title='$title',
                                        data='$data'");
    
                    $msg = 'Success: image uploaded';
                }
            }
            elseif (isset($_GET['title']))      // isset(..title) needed
                $msg = 'Error: file not loaded';// to make sure we've using
                                                // upload form, not form
                                                // for deletion
    
            if (isset($_POST['del'])) // If used selected some photo to delete
            {                         // in 'uploaded images form';
                $imageid = intval($_POST['del']);
                mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
                $msg = 'Photo deleted';
            }
    
            if (isset($_POST['view'])) // If used selected some photo to delete 
            { // in 'uploaded images form'; 
                $imageid = intval($_POST['view']); 
                mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid"); 
    
                if(mysql_num_rows($result) == 1) 
                { 
                    $image = $row['myimage']; 
                    header("Content-type: image/gif"); // or whatever 
                    print $image; 
                    exit; 
                } 
            } 
        }
        else
        {
            $imageid = intval($_POST['del']);
    
            if ($_POST["action"] == "view")
            {
                $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
                                         FROM {$table}
                                        WHERE imageid=$imageid LIMIT 1");
    
                if (mysql_num_rows($result) == 0)
                    die('no image');
    
                list($ext, $imagetime, $data) = mysql_fetch_row($result);
    
                $send_304 = false;
                if (php_sapi_name() == 'apache') {
                    // if our web server is apache
                    // we get check HTTP
                    // If-Modified-Since header
                    // and do not send image
                    // if there is a cached version
    
                    $ar = apache_request_headers();
                    if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
                        ($ar['If-Modified-Since'] != '') && // not empty
                        (strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
                        $send_304 = true;                                     // imagetime
                }
    
                if ($send_304)
                {
                    // Sending 304 response to browser
                    // "Browser, your cached version of image is OK
                    // we're not sending anything new to you"
                    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);
    
                    exit(); // bye-bye
                }
    
                // outputing HTTP headers
                header('Content-Length: '.strlen($data));
                header("Content-type: image/{$ext}");
    
                // outputing image
                echo $data;
                exit();
            }
            else if ($_POST["action"] == "delete")
            {
                $imageid = intval($_POST['del']);
                mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
                $msg = 'Photo deleted';
            }
        }
    }
    ?>
    <html><head>
    <title>Save Photo(s) to Find</title>
    </head>
    <body>
    <?php
    if (isset($msg)) // this is special section for
                     // outputing message
    {
    ?>
    <p style="font-weight: bold;"><?=$msg?>
    <br />
    </p>
    <?php
    }
    ?>
    <h1>Save Find images </h1>
    <h2>Uploaded Find images:</h2>
    <form action="<?=$PHP_SELF?>" method="post">
    <!-- This form is used for image deletion -->
    
    <?php
    $result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
    if (mysql_num_rows($result) == 0) // table is empty
        echo '<ul><li>No images loaded</li></ul>';
    else
    {
        echo '<ul>';
        while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
        {
            // outputing list
            echo "<li><input type='radio' name='del' title, value='{$imageid}' />";
            echo "&nbsp;<small>{$title}</small>&nbsp;&nbsp";
            echo "<small>{$imagetime}</small></li>";
        }
    
        echo '</ul>';
    
        echo '<input type="submit" value="Delete selected" onclick="document.getElementById(\'action\').value=\'delete\'" />';
    
        echo '<input type="submit" value="View Photo" onclick="document.getElementById(\'action\').value=\'view\'" />';
    }
    ?>
        <input type="hidden" name="action" id="action" />
    </form>
    <h2>Upload new Find image:</h2>
    <form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
    <label for="title"></label>
    <label for="photo"></label>
    <label for="password"></label>
    <table border="0" cellpadding="0" cellspacing="0" bordercolor="#111111" width="38%">
      <tr>
        <td bgcolor="#FF9900" height="22" colspan="2"><p style="margin-left: 10"><b><font face="Verdana" size="2" color="#FFFFFF"> Upload a File</font></b></td>
      </tr>
      <tr>
        <td bgcolor="#FFE3BB" colspan="2"><p style="margin-left: 10; margin-right: 10"><font face="Verdana" size="2"> <br>
          Please select a file from your local computer to upload to our web server 
    
          for saving in our database. This file can be of any type you like. Once you 
    
          have chosen a file, please click on the &quot;Upload this file&quot; button below.&nbsp;
    
          &nbsp;<br>
          &nbsp;</font></td>
      </tr>
      <tr>
        <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> File Description:</font></td>
        <td width="66%" bgcolor="#FFE3BB"><input type="text" name="title" id="title" size="64"/></td>
      </tr>
      <tr>
        <td bgcolor="#FFE3BB"><span style="margin-left: 10"><font face="Verdana" size="2">File Location:</font></span></td>
        <td bgcolor="#FFE3BB"><input type="file" name="photo" id="photo"/></td>
      </tr>
      <tr>
        <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> <br>
                  <br>
          &nbsp;</font></td>
        <td width="66%" bgcolor="#FFE3BB"><input name="submit" type="submit" value="Upload This File"/></td>
      </tr>
    </table>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    </form>
    </body>
    </html>
    

    希望对你有用!!

    【讨论】:

    • 嗨,非常感谢您花时间回复我的帖子和代码建议。我已经用你的建议替换了我所拥有的,虽然我没有收到任何错误,但不幸的是,我的“查看照片”按钮仍然删除了文件。我认为答案在于开头的部分: echo "
    • ";但我不确定如何让脚本的“del”和“view”片段在同一输出行中工作。亲切的问候。
  • @IRHM 我不明白你的问题。
  • 嗨@Marcio,如果我没有说清楚,请道歉。上传照片文件后,我的表单会显示“单选”按钮、文件名以及保存日期和时间。然后,用户针对他们感兴趣的文件选择“单选”按钮,并且可以选择删除它或查看它。正如我所说,我可以让删除部分工作,但不能查看图像。这是我页面的链接。mapmyfinds.co.uk/development/uploadfile3.php
  • 非常感谢。很抱歉提出一个非常愚蠢的问题,但我对此比较陌生,但可以确认我正在替换这一行: echo '' ;与您提供的那个。亲切的问候
  • 我已经开始看你的好作品了!保重,再次感谢。
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签