0

I'm doing a webpage where the user needs to load a photo. Since this photo will be linked to a unique id, I want that foto to be transfered to the server and saved as NUMBER.jpg or NUMBER.png or whatever extension. So the event on an input type field is called, in javascritpt code, as follows:

   var file = document.getElementById("foto").files[0];
   document.getElementById("pathFoto").value = file.name;
   var formData = new FormData();
   formData.append('foto',file,file.name);
   var xhr = new XMLHttpRequest();
   xhr.open('POST','php/handler.php',true);
   xhr.onload = function() {
      if (xhr.status == 200){
         console.log("Done");
      }
      else{
         console.log("An error ocurred " + xhr.responseText);
      }
   }
   xhr.send(formData);

On the php side of things, this is what I do:

$image = $_POST["foto"];
file_put_contents("atest.jpg",$image);

Now the error I get is that "foto" is an undefined index. Can anyone tell me what I'm doing wrong?

aarelovich
  • 5,140
  • 11
  • 55
  • 106
  • 1
    Possible duplicate of [jQuery Ajax File Upload](http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) – Kamil Karkus Apr 26 '16 at 17:20

1 Answers1

0

Here's how i'ld have gone about it

var file = document.getElementById("foto").files[0];
var formData = new FormData();
formData.append('foto',file);

initial ajax request like you did above.....


xhr.send(formData);

you can always get the file name from the php. You dont have to append it.

in ur php, do

if(isset($_FILES['foto']['name])){

}

follow link for how to upload file in php http://www.w3schools.com/php/php_file_upload.asp

Mueyiwa Moses Ikomi
  • 1,069
  • 2
  • 12
  • 26
  • Thank you very much. It worked pefectly. To sum up I needed to change only the fact that the image file is in $_FILES['foto'] and then use the command in PHP move_uploaded_file($_FILES["foto"]["tmp_name"], "atest.jpg"); Thanks!!!! – aarelovich Apr 27 '16 at 08:48