【发布时间】:2020-06-28 12:03:37
【问题描述】:
在开始之前,让我说我已经参考了许多其他帖子来解决我的问题,但我无法正确解决或找到针对我的问题的解决方案。这就是我在这里提出问题的原因。
让我开始吧,我目前正在模态中使用一些表单元素。所有表单元素都通过我现在的ajax提交并存储在mysql db中。
但是当我将文件上传元素添加到表单时,我的 ajax 不提交表单并且不反映在 mysql db 中。
HTML:
<div class="col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
<label style="color:#333D79FF; font-size:15px;">Upload Files </label>
<input type="file" name="srfile" id="srfile" class="form-control has-feedback-left" accept=".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx"/>
<span class="fas fa-upload form-control-feedback left text-info" aria-hidden="true"></span>
<span id="info">Only</span> .jpg, .jpeg, .png, .pdf, .doc, .docx, .xls, .xlsx files allowed. Max File Size 2 MB
</div>
我使用引导验证器来验证我的表单元素,验证后将其提交给 php 并提交给 mysql db。
查询:
$(document).ready(function() {
.on('success.form.bv', function(e) {
// Prevent submit form from page loading or refreshing
e.preventDefault();
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'firstname' : $('input[name=firstname]').val(),
'lastname' : $('input[name=lastname]').val(),
'gender' : $('input[name=gender]').val(),
'address' : $('input[name=address]').val(),
'city' : $('select[name=city]').val(),
'state' : $('select[name=state]').val(),
'country' : $('select[id=country').val(),
'aboutyourself' : $('textarea[name=aboutyourself]').val(),
'uploadfile' : $('input[type=file]').val(),
'send' : $('button[name=send]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use POST
enctype : 'multipart/form-data',
url : 'pages/insert.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
//log to the console form data in object form
//console.log(JSON.stringify(formData));
// log responce data to the console so we can see
console.log(data);
// ALL GOOD! just show the success message!
$(".status").html(data.status);
$(".msg").html(data.msg);
if (data.status_code===200) {
$('#status').html(data.status);
$('#msg').html(data.msg);
} else {
$('#statuserror').html(data.status);
$('#msgerror').html(data.msg);
}
});
});
});
我的 insert.php
if(isset($_POST['send'])){
$firstname=$_POST['firstname'];
......
.....
.....
etc..,
//File Upload
if(isset($_FILES['uploadfile'])){
$errors= array();
$file_name = $_FILES['uploadfile']['name'];
$file_size = $_FILES['uploadfile']['size'];
$file_tmp = $_FILES['uploadfile']['tmp_name'];
$file_type = $_FILES['uploadfile']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['uploadfile']['name'])));
$extensions= array("jpeg","jpg","png","pdf","doc","docx","xls","xlsx");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
$adduser=$link->prepare("INSERT INTO `users` (`firstname`,`lastname`,`gender`,`address` ,`city` ,`state` ,`country` ,`aboutyourself` ,`file`) VALUES (?,?,?,?,?,?,?,?,?)");
$adduser->bind_param('sssssssss', $firstname, $lastname, $gender, $address, $city, $state, $country, $aboutyourself, $file_name);
$adduser->execute();
if($adduser) {
$success = array(
'status' => 'Success!',
'status_code' => 200,
'msg' => 'User has been added.');
echo json_encode($success);
}else {
$error = array(
'status' => 'Error!',
'status_code' => 404,
'msg' => 'Error occurred in adding user. Please modify and try again.');
echo json_encode($error);
}
}
我的问题是,当我在插入查询中添加 $file_name 时,既不会插入值,也不会上传文件。否则,当我不使用 $file_name 值时,所有其他值都将添加到数据库中。
注意:请理解我使用了各种输入字段,例如名字、姓氏、地址等。虽然我没有在上面的 HTML 代码中显示这些代码,只是为了减少代码。希望你能理解
我哪里做错了。请帮忙。感谢您的积极回应。
更新: 对于我上面的 ajax formdata 变量,我进行了如下更改
var formData = {
'firstname' : $('input[name=firstname]').val(),
'lastname' : $('input[name=lastname]').val(),
'gender' : $('input[name=gender]').val(),
'address' : $('input[name=address]').val(),
'city' : $('select[name=city]').val(),
'state' : $('select[name=state]').val(),
'country' : $('select[id=country').val(),
'aboutyourself' : $('textarea[name=aboutyourself]').val(),
'send' : $('button[name=send]').val()
};
formData.append("uploadfile",$('input[type=file]')[0].files[0]);
上传文件没有成功
【问题讨论】:
-
您无法通过读取文件输入字段的
.val()来执行文件上传。 stackoverflow.com/questions/166221/… -
谢谢。您能否建议正确声明代码
-
你觉得我刚刚发布那个链接是为了……?!?
-
是的,我指的是您的链接。我已经在我的 ajax 中分配了数据:formData,现在如何合并这些数据:new FormData($('#formWithFiles')[0]), ????
-
这是两个完全不同的东西,你只是碰巧有一个名为
formData的变量。如果您只想发送 all 表单的字段 - 然后不要单独添加它们,只需将整个表单元素传递给 FormData 构造函数,然后它将创建完整的表单数据提交为您设置。
标签: php jquery ajax file-upload