显示图像 - 斑点 - 不正确
我在某个地方犯了严重错误。我正在尝试在 php 中显示 MySQL 表中的图像。我将从头开始。
uploadform
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br />
<input type="submit" value="Upload file">
</form>
<p>
<a href="list_files.php">See all files</a>
</p>
</body>
</html>
add_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'mydb');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
?>
显示图像
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$id = 1;
if(!isset($id) || empty($id) || !is_int($id)){
die("Please select your image!");
}else{
$query = mysql_query("SELECT * FROM file WHERE id='".$id."'");
$row = mysql_fetch_array($query);
$content = $row['data'];
header('Content-type: image/jpg');
echo $content;
}
?>
我的输出是这样的:����JFIFHH��C
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
imagecreatefromstring
和imagejpeg
You need to use
imagecreatefromstring
andimagejpeg
在您需要从数据库中编码 blob 的图像数据中尝试此操作
try this in the image data you need encoded the blob from database