当前位置: 首页 > 知识库问答 >
问题:

从提交表单上传图像到mysql数据库并在DIV中显示图像?

吴浩皛
2023-03-14

我是PHP的新手,需要在一个项目中弄清楚这一点--我用HTML制作了一个image submit表单,它将div中的img更改为使用该表单选择的图像。下面是我如何完成的:

echo '<div class="img-container">';
echo '<img class="userimg" src="../images/backgroundplanet.png" />';
echo '<img class="testimg" src="" />'; //stores image from php file
echo '</div>';
echo '<div class="upload-button">Edit Profile</div>';
echo '<input class="file-upload" enctype="multipart/form-data" type="file" name="submit" accept="image/*"/>';
echo '</div>';

而且

$(document).ready(function() {


    var readURL = function(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.userimg').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }


    $(".file-upload").on('change', function(){
        readURL(this);
    });

    $(".upload-button").on('click', function() {
       $(".file-upload").click();
    });
});

我需要将这个图像上传到我为每个用户在MySql数据库中的medium Blob创建的列中。我尝试了许多不同的方法(尝试了$sql=new mysql等),但不知道我在做什么。

我现在正在学习本教程-http://www.sevenkb.com/php/how-to-insert-upload-image-into-mysql-database-using-php-and-how-to-display-an-image-in-php-from-mysql-database/,并编写了以下内容,用于将图像上传到数据库:

if(!isset($_FILES['upload_image']))
 {
 echo '<p>Please Select Image to Upload</p>';
 }
else
 {
 try {
 upload();

 echo '<p>Image Uploaded into MySQL Database as LONGBLOB Using PHP </p>';
 }
 catch(Exception $e)
 {
 echo '<h4>'.$e->getMessage().'</h4>';
 }
 }

function upload(){
/*** check if a file was uploaded ***/
echo '<p>you uploaded</p>';

if(is_uploaded_file($_FILES['upload_image']['tmp_name']) && getimagesize($_FILES['upload_image']['tmp_name']) != false)
 {
 /*** get the image info. ***/
 $size = getimagesize($_FILES['upload_image']['tmp_name']);
 /*** assign our variables ***/
 $type = $size['mime'];
 $imgfp = fopen($_FILES['upload_image']['tmp_name'], 'rb');
 $size = $size[3];
 $name = $_FILES['upload_image']['name'];
 $maxsize = 99999999;


 /*** check the file is less than the maximum file size ***/
 if($_FILES['upload_image']['size'] < $maxsize )
 {
 /*** connect to db ***/
 $dbh = new PDO("mysql:host=localhost;dbname=sqlserver", 'username', 'password');

 /*** set the error mode ***/
 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 /*** our sql query ***/
 $stmt = $dbh->prepare("INSERT INTO img (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");

 /*** bind the params ***/
 $stmt->bindParam(1, $type);
 $stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
 $stmt->bindParam(3, $size);
 $stmt->bindParam(4, $name);

 /*** execute the query ***/
 $stmt->execute();
 }
 else
 {
 /*** throw an exception is image is not of type ***/
 throw new Exception("File Size Error");
 }
 }
else
 {
 // if the file is not less than the maximum allowed, print an error
 throw new Exception("Unsupported Image Format!");
 }
}

但图像没有上传,也没有出现在我在数据库中创建的新列中。页面上唯一显示的是“请选择图像上传”

这里怎么了?最终,我需要在一个div中重复这个。我该拿这个怎么办?

尝试运行示例时:

输入“我的表名”时出错:

共有1个答案

贲铭
2023-03-14

我使用了这个链接“http://www.formget.com/ajax-image-upload-php/”中的代码来获取您需要的内容。这段代码除了将文件保存到文件夹之外,还将其保存到数据库中。我制作了一个文件夹images来存储图像文件和两个php文件,一个显示前端html表单和javascript代码,另一个用于上传和显示。HTML代码“index.php”如下所示

null

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
<input type="hidden" name="image_id" id="image_id" value="2" class="submit" />
</div>
</form>
</div>
<h4 id='loading' >loading..</h4>
<div id="message"></div>

<style>
.userimg {
	width: 50px;
	height:auto;
	
}
</style>

<script type="text/javascript">

  $(document).ready(function (e) {
		$("#uploadimage").on('submit',(function(e) {
		e.preventDefault();
	    $("#message").empty();
		$('#loading').show();
		$.ajax({
		url: "upload.php", // Url to which the request is send
		type: "POST",             // Type of request to be send, called as method
		data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
		contentType: false,       // The content type used when sending data to the server.
		cache: false,             // To unable request pages to be cached
		processData:false,        // To send DOMDocument or non processed data file it is set to false
		success: function(data)   // A function to be called if request succeeds
		{
		$('#loading').hide();
		$("#message").html(data);
		}
		});
		}));
		
		// Function to preview image after validation
		$(function() {
		$("#file").change(function() {
		$("#message").empty(); // To remove the previous error message
		var file = this.files[0];
		var imagefile = file.type;
		var match= ["image/jpeg","image/png","image/jpg"];
		if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
		{
		$('#previewing').attr('src','noimage.png');
		$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
		return false;
		}
		else
		{
		var reader = new FileReader();
		reader.onload = imageIsLoaded;
		reader.readAsDataURL(this.files[0]);
		}
		});
		});
		function imageIsLoaded(e) {
		$("#file").css("color","green");
		$('#image_preview').css("display", "block");
		$('#previewing').attr('src', e.target.result);
		$('#previewing').attr('width', '250px');
		$('#previewing').attr('height', '230px');
		};
});

</script>
<style>
body {
font-family: 'Roboto Condensed', sans-serif;
}
h1
{
text-align: center;
background-color: #FEFFED;
height: 70px;
color: rgb(95, 89, 89);
margin: 0 0 -29px 0;
padding-top: 14px;
border-radius: 10px 10px 0 0;
font-size: 35px;
}
.main {
position: absolute;
top: 50px;
left: 20%;
width: 450px;
height:530px;
border: 2px solid gray;
border-radius: 10px;
}
.main label{
color: rgba(0, 0, 0, 0.71);
margin-left: 60px;
}
#image_preview{
position: absolute;
font-size: 30px;
top: 100px;
left: 100px;
width: 250px;
height: 230px;
text-align: center;
line-height: 180px;
font-weight: bold;
color: #C0C0C0;
background-color: #FFFFFF;
overflow: auto;
}
#selectImage{
padding: 19px 21px 14px 15px;
position: absolute;
bottom: 0px;
width: 414px;
background-color: #FEFFED;
border-radius: 10px;
}
.submit{
font-size: 16px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 300px;
border-radius: 5px;
padding: 10px 0;
outline: none;
margin-top: 20px;
margin-left: 15%;
}
.submit:hover{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
#file {
color: red;
padding: 5px;
border: 5px solid #8BF1B0;
background-color: #8BF1B0;
margin-top: 10px;
border-radius: 5px;
box-shadow: 0 0 15px #626F7E;
margin-left: 15%;
width: 72%;
}
#message{
position:absolute;
top:120px;
left:815px;
}
#success
{
color:green;
}
#invalid
{
color:red;
}
#line
{
margin-top: 274px;
}
#error
{
color:red;
}
#error_message
{
color:blue;
}
#loading
{
display:none;
position:absolute;
top:50px;
left:850px;
font-size:25px;
}
</style>
 类似资料:
  • 我试图通过在控制器中执行以下操作在数据库中上载多个图像: 公共函数存储(请求$request){ 它采用图像表单,并将所选图像存储在public/image文件夹中,但在数据库中,它存储具有相同图像名称的所有图像。在显示的同时,它会多次显示相同的图像。 我知道这里的人有解决这个问题的办法,也许会有更好的主意。所以请帮我解决这个问题。提前谢谢。 上面的“完成”方法不适合我,因此我在控制器中执行了此操

  • 日安!我正在尝试搜索一个从Android上传一个图像文件到一个在线MySQL数据库的基本教程,但是我找不到任何。 我现在正在做一个activity,可以把用户的个人资料图片从Android上传到在线服务器上。 我需要的是像显示一个按钮,当它被点击时,用户可以从文件中选择一个图像。有人能指导我做这件事吗?提前道谢!

  • 我是姜戈的初学者,对一件事很着迷,我不知道该怎么做。我想显示一个存储在数据库中的图像到我的模板。图像上载到文件夹“static/img”。 这是我的数据库: 这是我的模板: 我的views.py: 使用TEMPLATE_DIRS、STATIC_ROOT和static_url更新settings.py。

  • 但是宽度和高度较低的图像成功地加载到图像视图中! 有人能告诉我代码有什么问题吗?我做错了什么?我只想从库中导入相机图像,并在图像视图中显示它们!

  • 问题内容: 我需要在手机中打开我的画廊,然后选择一张在活动中在imageview中打开的图片..没什么困难..但是我在模拟器(genymotion)中有完美的代码和thise代码可以运行..但是在小米Mi4上却没有。 打开画廊选择项目,什么也没有。 我没有更多的电话了:( 我尝试下载一些与此主题相关的示例,并且每个示例都是相同的。 您是否有一些从图库中选择图像并在imageview中显示的项目?如