【发布时间】:2014-08-04 03:50:11
【问题描述】:
这是我第一次来这里。
我目前正在创建一个表格,将数据字符串插入 mysql 数据库并一起上传图像。图像名称必须保存在mysql数据库中,文件必须移动到一个文件夹中,我们将其命名为“image/”文件夹。
我使用 jquery 来插入数据。以下是我尝试过的一段代码:
表格:
<form enctype="multipart/form-data" method="post" action="" id="formBerita">
<div>
Title:
<div><input type="text" id="title" name="the_title" placeholder="Your title here..." autocomplete="off"></div>
</div>
<div>
Content :
<div><textarea id="content" name="the_content"></textarea></div>
</div>
<div>
<input type="hidden" name="max_size" value="300000">
Image:
<div><input id="img" name="the_img" type="file" /></div>
</div>
<div>
<input type="button" id="btnSave" value="Save">
</div>
用于插入的jQuery:
<script>
$(document).ready(function(){
$('#btnSave').on('click', function(){
var title = $("#title").val();
var content = $("#content").val();
var img = $("#img").val();
var dataContent = 'title='+title+'&content='+content+"&img="+img;
if(!title){
alert("You must fill the title!");
$("#title").focus();
}
else {
$.ajax({
type: "post",
url: 'includes/saveContent.php',
data: dataContent,
beforeSend: function() {
respon.contentColumn.append(respon.loader); //just loader before saving the data
},
success: function(datas) {
respon.contentColumn.find(respon.loader).remove();
}
});
}
});
});
</script>
保存内容.php 文件:
<?php
$title = $_POST['title'];
$content = $_POST['content'];
$img = $_POST['img'];
$query = "INSERT INTO tbl_content VALUES('','$title','$content','$img')";
mysql_query($query);
?>
到目前为止,上面的代码运行良好。但是,我仍然对如何使用 jQuery 和 PHP 上传和移动图像文件到某个目录或文件夹感到困惑。
众所周知,一般在php中我们使用:
move_uploaded_file($tempNama=$_FILES['fileName']['tmp_name'], $fileDestination);
用于将图像文件移动到目标文件夹。
那么,问题是:我应该添加什么来完成我的代码,以便可以上传图像文件并将其移动到目标目录?
【问题讨论】:
-
只想指出两点 1) 不要使用mysql_*!它已被弃用。使用 PDO 准备好的语句或 mysqli。此外,请务必在将输入输入数据库之前对其进行清理!