我希望将图像直接存储在数据库中,而不将其存储在我的资源管理器上的文件夹中。如果可能的话怎么样?我使用php
和mysql
数据库来存储图像,我已经定义了数据类型LONGBLOB
来将图像存储在数据库中。以下是我的代码:
<?php
$conn = mysqli_connect("localhost","root","")or die(mysqli_error($conn));
mysqli_select_db($conn,'image') or die(mysqli_error($conn));
if(isset($_REQUEST['submit'])){
$old = $_FILES['img']['tmp_name'];
$new = $_FILES['img']['name'];
move_uploaded_file($old,$new);
echo $sql = "INSERT INTO img(`img_name`) VALUES('$new')";
$exe = mysqli_query($conn,$sql);
if($exe){
echo "Image Uploaded Successfully....";
}
}
echo $query = "Select `img_name` from `img`";
$ex = mysqli_query($conn,$query);
?>
<html>
<body>
<form method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<div>
<input type="file" name="img"/>
</div>
<div>
<input type="submit" name="submit" value="Upload"/>
</div>
<?php
while($res = mysqli_fetch_array($ex)){
?>
<div>
<img height="50" width="50" src="<?php echo $res['img_name'];?>"/><br/>
</div>
<?php } ?>
</form>
</body>
</html>
答案 0 :(得分:1)
您需要将图像转换为base64。像这样的东西:
$path = $_FILES['img']['tmp_name'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
如果可能的话,最好将其保存为字符串而不是BLOB。如果必须是BLOB,则必须转换字符串,然后在从数据库中检索时将其转换回来。如果将其存储为字符串,则图像甚至可以使用base64作为图像的src。
答案 1 :(得分:0)
move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
$instr = fopen("latest.img","rb");
$image = addslashes(fread($instr,filesize("latest.img")));
mysql_query ("insert into pix (mgdata) values ('".image."')");
删除上传的图片后,图片将显示在DB
中您可以将图像从数据库发送到浏览器
$gotten = @mysql_query("select * from pix order by pid desc limit 1");
if ($row = @mysql_fetch_assoc($gotten)) {
$title = htmlspecialchars($row[title]);
$bytes = $row[imgdata];
}
// If this is the image request, send out the image
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
?>