Home > OS >  Upload image to server using Jquery
Upload image to server using Jquery

Time:10-16

I need your help to upload an image on my server. Indeed, with this code, I have an array(0) {} response while the values are well populated. No image is uploaded... thank you for your help, here are my two files:

index.php

<input type="file" id="txt_image_user" name="txt_image_user" accept="image/*" required >

<script>
function upload_image() {
    var handle      = document.getElementById("txt_handle").value;
    var reference   = document.getElementById("txt_reference").value;
    
    var fd          = new FormData();
    var files       = $('#txt_image_user')[0].files[0];
    fd.append('txt_image_user', files);

    $.ajax({
        type: 'POST',
        url: '_upload-image.php',
        cache: false,
        data: {fd:fd, handle:handle, reference:reference},
        contentType: false,
        processData: false,
        error: function (e) {console.log('Ajax Error', e);alert('Erreur Ajax');},
        success: function(response){
                console.log(response);
        },
    });
}
</script>

_upload-image.php

<?php require($_SERVER['DOCUMENT_ROOT']."/ew-includes/config.php");

var_dump($_POST);

$PathImage = $_SERVER['DOCUMENT_ROOT']."/ew-content/images/images-clients/";
if (!is_dir($PathImage)) {mkdir($PathImage);}

if(isset($_POST["handle"])) {
if(is_array($_POST["handle"]))          {$handle        = implode(", ", $_POST['handle']);} else {$handle = $_POST['handle'];}
if(is_array($_POST["reference"]))       {$reference     = implode(", ", $_POST['reference']);} else {$reference = $_POST['reference'];}

$img_name = $_FILES["txt_image_user"]["name"];
$img_tmp  = $_FILES["txt_image_user"]["tmp_name"];

$filename   = "ew".$reference."_".$handle."_".date("YmdHi");
$ext        = pathinfo($img_name, PATHINFO_EXTENSION);
$photo      = $filename.".".$ext;
$resultat   = move_uploaded_file($img_tmp, $PathImage.$photo);

echo "img_name: ".$img_name."\n";
echo "img_tmp: ".$img_tmp."\n";
echo "ext: ".$ext."\n";
echo "photo: ".$photo."\n";
echo "resultat: ".$resultat."\n";

}

Thanks for your help. I specify that I am new in Jquery

CodePudding user response:

That's not the way to use FormData it should be the data. You can append other values to it.

function upload_image() {
  var handle = document.getElementById("txt_handle").value;
  var reference = document.getElementById("txt_reference").value;

  var fd = new FormData();
  var files = $('#txt_image_user')[0].files[0];
  fd.append('txt_image_user', files);
  fd.append('handle', handle);
  fd.append('reference', reference);

  $.ajax({
    type: 'POST',
    url: '_upload-image.php',
    cache: false,
    data: fd,
    contentType: false,
    processData: false,
    error: function(e) {
      console.log('Ajax Error', e);
      alert('Erreur Ajax');
    },
    success: function(response) {
      console.log(response);
    },
  });
}
  • Related