努力用php显示blob图像

时间:2012-09-30 17:56:48

标签: php html mysql image blob

我正在构建一个简单的网站,我想允许用户上传和更改他们的头像。目前我已经能够将图像上传到mysql数据库,存储为blob,代码如下:

//connected to DB, userID fetched

$image = $FILES['fileToUpload']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);

$sql = "UPDATE tbUsers SET profileImage = '".$content."' WHERE userID = ".userID;
$result = mysql_query($sql) or die (mysql_error());

当我上传后从phpmyadmin下载文件时,它们会保存为.bin文件,但可以正常查看。我不确定这是否正确。 我显示图像的代码如下:

HTML:

<?php echo '<img src ="showPic.php?q='.$_SESSION['profile'].'"/>'; ?>

PHP:

if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
  $con = mysql_connect("localhost", "root", "");
  $mysql_select_db("projectDB");
  $sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
  $result = mysql_query($sql) or die (mysql_error());

  header('Content-type: image/jpeg');
  $row = mysql_fetch_object($result);
  echo $row['image_data'];
}

我不确定我是否正在尝试以正确的方式显示图像,我们将非常感谢任何帮助(更正/替代解决方案):)

2 个答案:

答案 0 :(得分:1)

你可以这样做:

if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
  $con = mysql_connect("localhost", "root", "");
  $mysql_select_db("projectDB");
  $sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
  $result = mysql_query($sql) or die (mysql_error());

  $content = mysql_result($result,0,"file_content");
  $name = mysql_result($result,0,"file_name");
  $type = mysql_result($result,0,"file_type");
  $size = mysql_result($result,0,"file_size");
  header("Content-type: $type");

  echo $content

}

注意:您应该在保存BLOB数据的表中使用这些列

file_name =保存文件名

$_FILES['file']['name']

file_type =用于保存文件类型

$_FILES['file']['type']

file_size =保存文件大小

$_FILES['file']['size']

答案 1 :(得分:0)

您选择此

$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];

并参考未选择的列

echo $row['image_data'];