html中从本地上传图片并存到数据库
时间: 2023-11-29 14:05:12 浏览: 77
图片上传本地和数据库程序
4星 · 用户满意度95%
在HTML中上传图片并将其存储到数据库需要使用服务器端脚本来实现。以下是一般的步骤:
1. 在HTML表单中添加一个input元素,type属性为“file”,用于选择文件:
```
<form method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
```
2. 在服务器端接收表单数据并将图片存储到数据库中。在这里我们假设使用PHP作为服务器端脚本。
首先需要连接到数据库:
```
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
```
然后获取上传的文件并将其存储到服务器上的一个目录中:
```
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
```
最后将图片的路径存储到数据库中:
```
$sql = "INSERT INTO images (image_path) VALUES ('$target_file')";
$result = mysqli_query($conn, $sql);
```
完整的PHP代码如下所示:
```
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_FILES["image"])){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
$sql = "INSERT INTO images (image_path) VALUES ('$target_file')";
$result = mysqli_query($conn, $sql);
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
```
注意,上述代码仅供参考,实际应用中需要对上传文件的类型和大小进行验证和限制,并且需要防止SQL注入等安全问题。
阅读全文