我正在尝试将图像存储到路径中,然后将它们上传到我的数据库中。数据库被称为"存储"我使用的表格被称为"图像"包含3个字段:id,name(varchar),image(longblob)。表格如下:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload an Image</title>
</head>
<body>
<form action="upload_file.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="262144000" />
<p>File:</p>
<input type="file" name="image" accept="image/jpeg" accept="image/jpg" accept="image/png" accept="image/gif">
<input type="submit" value="Upload" name="submit" />
</form>
</body>
</html>
&#13;
upload_file.php是:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file)){
echo "<p>Please select an image.</p>";
} else {
//$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "<p>Sorry, this is not an image.</p>";
} else {
echo "<p>File is an image. Processing...</p>";
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')")){
echo "<p>Problem uploading image:".mysql_error()."</p>";
} else {
$lastid = mysql_insert_id();
echo "<p>Success!</p>";
echo "<img src=get.php?id=$lastid>";
}
}
}
error_reporting(-1);
?>
&#13;
get.php是:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
$id = $_REQUEST['id'];
$image = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_array($image);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
?>
&#13;
图像已上传,但未显示。相反,我得到一个破碎的图像图标,我不明白为什么。有人能帮我吗??
答案 0 :(得分:1)
尝试逐步解决此问题
此过程可以识别为三个部分并快速拆分。 HTML表单,PHP上传和保存到数据库进程,以及从数据库进程加载。
这只是一个示例清单。但您可以更改此设置并添加更多步骤。
另外,请考虑更新为MySQLi。您正在使用可能导致安全问题的已弃用功能。有关该主题的许多信息来源可以在网上找到。
答案 1 :(得分:0)
使用此代码
更正get.php代码<?php
//Connect to database
$conn = mysql_connect("localhost", "tester", "");
if (!$conn) {
die("Could not connect to MySQL");
}
if (!mysql_select_db("tester")) {
die("Could not open database:" . mysql_error());
}
$id = $_REQUEST['id'];
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
您必须更改数据库名称和用户自己的
这些是我改变的部分:
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
echo base64_decode($image);