简体   繁体   中英

AJAX POST file upload control to PHP file

Using AJAX I'm posting file upload control value to PHP file.

file upload control below:

<input class="form-control" type="file" id="policy_image" name="policy_image" accept="image/*">

AJAX Call below:

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');
    }
});

In my PHP file I getting the posted value like below

PHP file:

$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....";
  }
}

now I'm getting error like Undefined index: policy and Undefined index: policy_image

Try this:

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);
    }
});

Php:

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";
    }
}
    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";
        }

    ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM