gpt4 book ai didi

php - 如何上传图像代码并将路径保存到mysql db

转载 作者:搜寻专家 更新时间:2023-10-31 21:17:53 25 4
gpt4 key购买 nike

如何编写上传图片和保存路径到mysql数据库的代码?我试过了,但都没有用。

最佳答案

一种方法是上传图片并将其存储在服务器上的文件夹中,并将名称保存到mysql数据库中。这是一个例子::

首先我们将创建一个表单来上传::

//文件.html

Upload your file to the database...
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input name="picture" type="file" id="picture" size="50">
<input name="upload" type="submit" id="upload" value="Upload Picture!">
</form>

然后我们创建upload.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title> Upload Image </title>
<?php
// if something was posted, start the process...
if(isset($_POST['upload']))
{

// define the posted file into variables
$name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
$type = $_FILES['picture']['type'];
$size = $_FILES['picture']['size'];

// if your server has magic quotes turned off, add slashes manually
if(!get_magic_quotes_gpc()){
$name = addslashes($name);
}

// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, $size);
$content = addslashes($content);
fclose($extract);

// connect to the database
include "connect.php";

// the query that will add this to the database
$addfile = "INSERT INTO files (name, size, type, content ) VALUES ('$name', '$size', '$type', '$content')";
mysql_query($addfile) or die(mysql_error());
if(!empty($_FILES))
{
$target = "upload/";
$target = $target . basename( $_FILES['picture']['name']) ;
$ok=1;
$picture_size = $_FILES['picture']['size'];
$picture_type=$_FILES['picture']['type'];
//This is our size condition
if ($picture_size > 5000000)
{
echo "Your file is too large.<br>";
$ok=0;
}


//This is our limit file type condition
if ($picture_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}

//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}

//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['picture']['name']). " has been uploaded <br/>";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
}


mysql_close();

echo "Successfully uploaded your picture!";
}else{die("No uploaded file present");
}

?>
</head>

<body>

<div align="center">
<img src="upload/<?php echo $name; ?>"
<br />
<a href="form.html">upload more images</a>
</div>

</body>
</html>

//getpicture.php

**//最后是connect.php**

关于php - 如何上传图像代码并将路径保存到mysql db,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4545582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com