Upload Ajax - Php

Asked

Viewed 572 times

1

I am trying to upload a PDF file via Ajax and Php. But I can’t.

HTML

<script>

   var client = new XMLHttpRequest();

   function upload(){

      var file = document.getElementById("uploadfile");

      var formData = new FormData();
      formData.append("upload", file.files[0]);
      formData.append("MAX_FILE_SIZE", '30000');
      formData.append("userfile", 'pdf');

      client.open("post", "upload.php", true);
      client.send(formData);

   }

   client.onreadystatechange = function(){
      if (client.readyState == 4 && client.status == 200){
         $("#resposta").html(client.responseText);
      }
   }

</script>

<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />

PHP

<?php

$uploaddir = 'uploads/';
$uploadfile = $uploaddir.basename($_FILES['userfile']['name']);

echo '<pre>';

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "Arquivo válido e enviado com sucesso.\n";
} else {
    echo "Possível ataque de upload de arquivo!\n";
}

echo "<br><br><br>";

echo 'Aqui está mais informações de debug:';
print_r($_FILES);

print "</pre>";

?>

PHP returns no error, but the file is not uploaded.

4 answers

2


In addition to the situation cited by @Sergio, there are other problems:

  1. For each ajax execution a new one is required new XMLHttpRequest(), that is, you are using only one new XMLHttpRequest() for all requests you will make, this will not work.

  2. For every new xmlhttprequest, you must define a new .onreadystatechange = function(){};

Corrected code:

function upload(){
  var client = new XMLHttpRequest();
  client.open("post", "upload.php", true);
  client.onreadystatechange = function(){
     if (client.readyState == 4 && client.status == 200){
        $("#resposta").html(client.responseText);
     }
  };

  var file = document.getElementById("uploadfile");

  var formData = new FormData();
  formData.append("upload", file.files[0]);
  formData.append("MAX_FILE_SIZE", '30000');
  formData.append("userfile", 'pdf');

  client.send(formData);
}
  • 1

    Great, thank you very much ! Improved a lot

1

Mute $_FILES['userfile'] for uploadfile as you have in the name of HTML. O $_FILES get the name of input name="uploadfile" /> and place it in the array.

You can also check what files have via var_dump($_FILES); debug.

1

Try adding to your Xmlhttprequest:

client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

I know yet another method to perform the upload, having it only the limitation of allowing to send one file at a time only:

function upload(){
    var inputFile = document.getElementById("uploadfile");
    var file = inputFile.files[0];
    var formData = new FormData();

    client.open("post", "upload.php", true);
    client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");       
    client.setRequestHeader("X-File-Name", file.name);
    client.setRequestHeader("X-File-Size", file.size);

    client.send(file);
}

And in PHP:

<?php

$filename = $_SERVER['HTTP_X_FILE_NAME'];
$filesize = $_SERVER['HTTP_X_FILE_SIZE'];

$in = fopen('php://input','r');
$out = fopen('uploads/'.$filename, 'x');
while($data = fread($in, 1024)) 
    fwrite($out, $data);
?>

0

In your form you added this here?

<form action="" method="post" enctype="multipart/form-data">

This makes the upload work properly.

  • Yeah, it’s still not working !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.