-1

I'm trying to upload a file using XMLHttpRequest() function to run a php script . Here is the HTML code

<form enctype="multipart/form-data" action="testupload.php" method="POST">
<input type="text" class="form-control input-lg" name="image_text" id="filename">
<input type="hidden" name="MAX_FILE_SIZE" value="51200000000" />
Send this file: <input name="usrfile" type="file" />
<input type="button" value="Send File" onclick="uploadtest()"/>
</form>

Here is javascript code

function uploadtest(){
    
        var file2 =document.getElementById("filename").value;

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
              
                
                }
        };                

        xmlhttp.open("GET", "testupload.php?fileID=" + file2 , true);
        xmlhttp.send();

    }

This is my PHP script

<?php

/if(!empty($_FILES['usrfile'])){
//    print_r($_FILES);
   // echo "goda";
 //   // File upload configuration
    $targetDir = "C:/wamp64/www/CMS_TEST2/uploads/";
    $allowTypes = array('mp4', 'jpg', 'png', 'jpeg', 'gif');
    
    // $fileName = basename($_FILES['file']['name']);
    $fileName = $_GET["fileID"];
    //  $fileName = "MCCT0001";
    $temp = explode(".", $_FILES["usrfile"]["name"]);
    $newfilename = $fileName.".".end($temp);
    $targetFilePath = $targetDir.$newfilename;
    
    
    // Check whether file type is valid
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
    if(in_array($fileType, $allowTypes)){
        // Upload file to the server
        if(move_uploaded_file($_FILES['usrfile']['tmp_name'], $targetFilePath)){
            echo "File is valid, and was successfully uploaded.\n";
        
            print_r($_FILES);
        }
    }
    
     
//}

?> 

If i call the php script using PHP isset form submit. file upload works. But the issue when i call the php script using ajax $_FILES returns empty. Can you please help me with what i'm doing wrong here

1 Answers1

1

The first problem is that you are using GET method in your AJAX request. GET requests cannot have a request body. To be more precise, a client can send a GET request having a body, but servers are implemented to ignore it. Note that you use POST method in the form.

The second problem is that you are not actually including the file data in your JavaScript code. There is an example on MDN website: see how FormData is used to send a file in the POST request

        function sendFile(file) {
            const uri = "/index.php";
            const xhr = new XMLHttpRequest();
            const fd = new FormData();
            
            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText); // handle response.
                }
            };
            fd.append('myFile', file);
            // Initiate a multipart/form-data upload
            xhr.send(fd);
        }

As a side note, for this kind of operation I recommend to look into HTML5 File API, to read the bytes of the file, and send them to the server. You can also chunk the bytes to make more web requests, to support uploading files of any size.

  • I still not able to get this work function uploadtest(){ const fileInput = document.querySelector("#fileInput"); console.log("ttest function"); const fd = new FormData(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } }; fd.append('file', fileInput); xmlhttp.open("POST", "testupload2.php", true); xmlhttp.send(fd); } – nskniranga1127 Oct 02 '20 at 08:32
  • I'm getting "usrfile" not defined php error – nskniranga1127 Oct 02 '20 at 08:36
  • Anyway thanks a lot for the explanation I also got a complete example code from this https://makitweb.com/how-to-upload-file-with-javascript-and-php/ – nskniranga1127 Oct 02 '20 at 09:23
  • I'm glad I could help a bit. I think you are getting "usrfile" is undefined because you should configure this name in the FormData, so: fd.append('usrfile', file); - I copied the example from MDN website and I didn't update it to match the field names you expect on the server side, in your PHP code – Roberto Prevato Oct 02 '20 at 10:43