我一直在搜索SO的解决方案并尝试过,但我发现的答案中没有一个解决了我的问题。所以就是这样。
我正在开发一个简单的Web应用程序,其中包含输入详细信息和文件上载(.docx文件)。我使用FormData
来处理表单数据,但服务器端操作仅适用于表单输入,如text, password, date
等。
这是我的JS代码;评论的行是我试过但没有用的行。
var myForm = $("#add-thesis-form");
var formData = new FormData(myForm);
//var formData = myForm.serialize();
$.ajax({
type: "POST" ,
url: "thesis-scripts/add_thesis.php",
data: formData
// processData: false,
// contentType: false
}).done(function(data){
$('#addThesisModal').modal('hide');
alert(data);
//alert("Successfully saved a record to the database. ");
showThesis();
});
我的PHP代码(使用Meekro DB)
$title = $_POST["title"];
$description = $_POST["description"];
$categoryId = $_POST["category_id"];
$collegeId = $_POST["college_id"];
$departmentId = $_POST["department_id"];
$uploadedBy = $_SESSION["user"];
$uploadedAt = DB::queryFirstField("SELECT NOW();");
$year = $_POST["thesis_year"];
$keywords = $_POST["keywords"];
$authors = $_POST["authors"];
//FILE UPLOAD
$targ_dir = "../uploads/";
$targ_file = $targ_dir . basename($_FILES["thesis"]["name"]);
$flagOk = 1;
$tempFolder = $_FILES["thesis"]["tmp_name"];
move_uploaded_file($tempFolder, $targ_file);
//!FILE UPLOAD
$result = DB::insert('theses', array(
"title" => $title,
"description" => $description,
"categoryId" => $categoryId,
"collegeId" => $collegeId,
"departmentId" => $departmentId,
"uploadedBy" => $uploadedBy,
"uploadedAt" => $uploadedAt,
"pubyear" => $year,
"filepath" => $targ_file,
"views" => 0,
"rating" => 0,
"keywords" => $keywords,
"authors" => $authors
));
我已经尝试了print_r($_FILES)
并且那个有效,但是这个没有。请帮我。谢谢。
设置contentType:false
会导致服务器在所有Undefined index
变量上抛出错误$_POST
。
答案 0 :(得分:0)
也许您的表单应包含enctype="multipart/form-data"
也许这会奏效:
$.ajax({
type: "POST" ,
url: "thesis-scripts/add_thesis.php",
data: "multipart/form-data"
...