Home > OS >  AJAX upload images from array to process with PHP
AJAX upload images from array to process with PHP

Time:08-24

I have a simple form so you can upload images. I store the uploaded images' properties in a array but I want to post this array to a PHP file using ajax. If I try to get the uploaded image: $_FILES['image1'], it returns an empty array. Any idea what I am doing wrong?

PS: It is important to store the images' properties in a array and pass it to a FormData.

var foo = []; var input = document.getElementById('input');
document.getElementById('add').addEventListener('click', () => {
  foo.push(input.files[0]);
});
document.getElementById('check').addEventListener('click', () => {
  console.log(foo);
});

document.getElementById('upload').addEventListener('click', () => {
  var fd = new FormData();
  for (let i = 0; i < foo.length; i  ) {
    fd.append('image' i, foo[i]);
  }

  $.ajax({ 
    enctype: "multipart/form-data",
    type: "POST",
    url: "path/to/php.file",
    data: fd,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function(data) { console.log(data); },
    error: function (err) { console.log(err); }
  });
});
<button id="add">ADD</button>
<button id="check">CHECK</button>
<button id="upload">UPLOAD</button>
<br><br>
<input type="file" id="input" placeholder="UPLOAD IMAGE">

And the PHP file:

<?php
    $arr = array();
    array_push($arr, $_FILES);
    die(json_encode($arr));
?>

CodePudding user response:

Or you need to check php.ini and check if the size of all the images you add exceeds "upload_max_filesize"

CodePudding user response:

I executed the code with two files. It seems that you can print the files successfully with the following code (PHP file)

    print_r($_FILES['image0']);
    print_r($_FILES['image1']);

I used jquery 3.5.1, for the ajax call.

I hope it helps.

  • Related