在postgresql表中存储映像文件失败



我正在尝试将图像文件存储在psql数据库表中。表"images"有两个字段,类型为integer&amp类型为byta的image。

我试图修改网上教程中的图像保存代码。但我的代码正在引发错误&警告

这是错误消息:

Notice: Undefined index: image in C:xampphtdocsmapsun.php on line 48
Warning: fopen(): Filename cannot be empty in C:xampphtdocsmapsun.php on line 50
cannot read image 

这些错误出现在if(isset($_POST["submit1"])){块内的线路上

如何纠正这些错误?

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Upload</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<?php
require("connection.php");
?>
<div class="container-fluid">
<h1 align="center">Test Form </h1>
<form action="" method="post" class="needs-validation" novalidate enctype="multipart/form-data"> 
<h2> Field </h2>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">Field ID</label>
<input type="number" class="form-control" name="field_id" id="field_id" placeholder="insert field id" value="" required>
<div class="valid-feedback">
0
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">IMG</label>
<input type="file" class="form-control" name="image" id="image" placeholder="insert image" value="" required>
<div class="valid-feedback">
</div>
</div>      
</div>
<button class="btn btn-primary" name="submit1" type="submit">Insert Image</button>
</form>

<?php
if(isset($_POST["submit1"])){
$file_name = $_POST["image"];
$img = fopen($file_name, 'r') or die("cannot read imagen");
$data = fread($img, filesize($file_name));
$es_data = pg_escape_bytea($data);
fclose($img);   

try {
$sql = "INSERT INTO images (field_id, image)
VALUES ('".$_POST["field_id"]."','.$es_data.')";
// echo "<meta http-equiv='refresh' content='0'>";
if ($conn->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}   
//$conn = null;
?>
</div>    
</body>
</html> 

文件存储在$_FILES超全局中。$_POST中没有图像
文件名将为$_FILES["image"]["tmp_name"]。这是php临时上传它的路径,您可以处理它

参考编号:https://secure.php.net/manual/en/reserved.variables.files.php
https://secure.php.net/manual/en/features.file-upload.php

PS:您的代码容易受到SQL注入的攻击。请使用准备好的报表或PDO。

最新更新