我正在尝试将图像文件存储在psql数据库表中。表“ images”具有两个字段,整数类型的“ id”和bytea类型的“ image”。
我试图通过网络上的教程修改图像保存代码。但是我的代码正在引发错误和警告。
这是错误消息:
Notice: Undefined index: image in C:\xampp\htdocs\maps\un.php on line 48
Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\maps\un.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 image\n");
$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>
答案 0 :(得分:1)
文件存储在$_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。