php获取jquery post文件上传,jQuery FormData POST – 用于文件上传

博客作者在尝试使用jQuery和FormData提交包含文件上传的表单到服务器,遇到非法调用错误。他们想知道如何正确初始化FormData对象以及在服务器端如何访问表单字段。服务器端代码使用PHP处理文件上传和数据库操作。问题集中在前端jQuery代码和后端如何配合处理文件上传。
摘要由CSDN通过智能技术生成

我正在尝试使用jQuery提交服务器端处理的完整表单.表单包含各种字段,包括文件上载选项.我正在尝试使用FormData来执行此操作,因为我不关心目前不支持它的浏览器.

我有以下(简化的)jQuery代码:

$("#create_event_form").submit(function(event) {

event.preventDefault();

var formData = new FormData($(this));

$.post(

"create_entity.php",

{ formData: formData },

function(data) {

var response = jQuery.parseJSON(data);

if(response.code == "success") {

alert("Success!");

} else if(response.code == "failure") {

alert(response.err);

}

}

);

});

我的服务器端如下所示:

require_once('includes/database.php');

$dbh = db_connect();

$response = array();

if($_SERVER['REQUEST_METHOD'] == "POST") {

// do some other stuff...

// upload entity picture and update database

$url = $_FILES['entity_pic']['name'];

if($url != "") {

if($type == "user") {

$pic_loc = "images/profiles/";

} else if($type == "chapter") {

$pic_loc = "images/chapters/";

} else if($type == "group") {

$pic_loc = "images/groups/";

} else if($type == "event") {

$pic_loc = "images/events/";

}

// upload the picture if it's not already uploaded

if(!file_exists($pic_loc . $_FILES['entity_pic']['name'])) {

move_uploaded_file($_FILES['entity_pic']['tmp_name'], $pic_loc . $url);

}

$image_query = "INSERT INTO image (entity_id, url, type) VALUES (:entity_id, :url, :type);";

$image_query_stmt = $dbh->prepare($image_query);

$image_query_stmt->bindParam(":entity_id", $entity_id);

$image_query_stmt->bindParam(":url", $url);

$image_query_stmt->bindValue(":type", $type);

if(!$image_query_stmt->execute()) {

die(print_r($image_query_stmt->errorInfo()));

}

}

echo json_encode($response);

}

?>

还有一些相关的HTML:

现在我得到一个非法的调用错误,大概是我的FormData对象的初始化.我一直在寻找如何使用jQuery做到这一点的例子,并且空洞.此外,我想澄清我的服务器端代码将工作.当我将formData作为“formData”传递给我的PHP脚本时,如何访问其中的字段?它会是“$_POST [‘formData’] [‘field_name’]”还是只是$_POST [‘field_name’]或其他完全不同的东西?

谢谢你的帮助.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值