php – Upload multiple files via ajax from an HTML file input

Question

I’m trying to upload files from a multiple file upload HTML input via ajax on a WordPress site but I keep getting a 400 error and I’m not sure why. My code is based on this tutorial.

jQuery:

$(document).on('change','input[type="file"]',function(){

  var fd = new FormData();
  var files_data = $(this); // The <input type="file" /> field

  // Loop through each data and create an array file[] containing our files data.
  $.each($(files_data), function(i, obj) {
      $.each(obj.files,function(j,file){
          fd.append('files[' + j + ']', file);
      })
  });

  fd.append('action', 'file_upload');

  fd.append('nonce', $('#file_upload_nonce').val());

  fd.append('application_id', $(this).closest('.application_question').attr('data-application-id'));

  $.ajax({
      type: 'POST',
      url: '/wp-admin/admin-ajax.php',
      data: fd,
      contentType: false,
      processData: false,
      success: function(response){
        console.log(response);
      }
  });

});

PHP:

function file_upload(){
  // Check the nonce first
  if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'file_upload' ) ) {
    echo 'Security validation failed.';
  } else {

    $application_id = $_POST['application_id'];

    foreach ( $_FILES['files']['name'] as $f => $name ) {

      move_uploaded_file( $_FILES["files"]["tmp_name"][$f], '/wp-content/supporting-evidence/' . $application_id . "https://wordpress.stackexchange.com/" . $_FILES["files"]["name"][$f] );

    }

  }
  wp_die();
}
add_action('wp_ajax_file_upload','file_upload');

What am I doing wrong here?

0
AJT 2 months 2023-02-07T06:37:22-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse