php - 努力用 php 显示 blob 图像

标签 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'];
}

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

最佳答案

你可以这样做:

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']

关于php - 努力用 php 显示 blob 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663608/

相关文章:

php - 如何关闭共享托管环境中特定目录的 php safe_mode off?

php - 哪个是 Windows 上最好的 PHP 编辑器?

PHP:如何在 Codeigniter 中获取上传文件的文件名和扩展名?

html - 我的 <a href 没有将我发送到文档中的元素

javascript - 使用 ASP.NET 服务器控件显示 div 的正确方法

php - Symfony 1.4 - MySql View 的 getPager 附加变量

mysql - 在sql查询中复制行

php - 通过单击字段名称使用来自 sql 查询的数据对 html 表进行排序

javascript - 将桌面拖放到浏览器 HTML5 Javascript

php - 在不删除每张表的情况下使用 Doctrine 更新 Schema?