使用AJAX我将文件上传控制值发布到PHP文件。
下面的文件上传控件:
<input class="form-control" type="file" id="policy_image" name="policy_image" accept="image/*">
下面的AJAX调用:
var file_data = $('#policy_image').prop('files')[0];
var policy_image = new FormData();
policy_image.append('file', file_data);
$.ajax({
type: 'post',
url: 'addpolicy.php',
data: {
'policy': $('#policy').val(),
'policy_image': policy_image
},
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
alert('Success');
}
});
在我的PHP文件中,我获得了如下所示的发布值
PHP文件:
$name = $_POST['policy'];
$imgFile = $_FILES['file']['name'];
$tmp_dir = $_FILES['file']['tmp_name'];
$imgSize = $_FILES['file']['size'];
$upload_dir = 'assets/img/policy/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
// allow valid image file formats
if(in_array($imgExt, $valid_extensions)){
// Check file size '5MB'
if($imgSize < 5000000) {
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else{
$errMSG = "Sorry, your file is too large.";
}
}
else{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
// if no error occured, continue ....
if(!isset($errMSG))
{
$stmt = $DB_con->prepare('INSERT INTO policy(name,image) VALUES(:name, :image)');
$stmt->bindParam(':name',$name);
$stmt->bindParam(':image',$userpic);
if($stmt->execute())
{
$successMSG = "new record succesfully inserted ...";
}
else
{
$errMSG = "error while inserting....";
}
}
现在我收到的错误如Undefined index: policy
和Undefined index: policy_image
答案 0 :(得分:0)
试试这个:
var file_data = $('#policy_image').prop('files')[0];
var form_data = new FormData();
form_data.append('policy_image', file_data);
$.ajax({
url : 'addpolicy.php',
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output);
}
});
腓:
if ( $_FILES['policy_image']['error'] > 0 ){
echo 'Error: ' . $_FILES['policy_image']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['policy_image']['tmp_name'], 'uploads/' . $_FILES['policy_image']['name']))
{
echo "File Uploaded Successfully";
}
}
答案 1 :(得分:0)
upload.php
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'addpolicy.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
alert(response);
}
});
});
addpolicy.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
echo "true";
}
?>