Failed to upload files using xmlHttpRequest js

Viewed 18

i'm learning javascript by using a book, and following one of the examples in the book to upload files using Ajax (with the xmlHttpRequest), the file is not beeing uploaded to the server. Here my js code:

const buttonNode = document.getElementById("button");
let boxDataNode = document.getElementById("boxinfo");

let fileInputNode = document.getElementById("file");
let files;

fileInputNode.onchange = (event) =>{
    files = event.target.files;
}

buttonNode.onclick = () =>{
    const file = files[0];
    let form = new FormData();
    form.append("file", file);

    let request = new XMLHttpRequest();
    request.responseType = "blob";
    request.onload = () =>{
        console.log(request.status); // i'm getting status 200
    }
    request.onloadstart = () =>{
        boxDataNode.innerHTML = "";
        let progress = document.createElement("progress");
        progress.value = 0;
        progress.max = 100;
        progress.innerHTML = "0%";
        boxDataNode.appendChild(progress);
    }
    let xmlupload = request.upload;
    xmlupload.onprogress = (event) =>{
        if(event.lengthComputable){
            let progress = document.getElementsByTagName("progress");
            let porcent = parseInt(event.loaded / event.total * 100);
            progress.value = porcent;
            progress.innerHTML = porcent + "%";
        }
    }
    request.open("POST", "mydomain.com/upload.php", true); // the php file in the server is empty
    request.send(form);
}

i can see a warning message in Cpanel, talking about a rule from the server's firewall here the error

following that error, i tried disabling ModSecurity in Cpanel, but it didn't work. So, here my question:

  • is my code wrong in any way or it should be working like this?. in the book's example there is not a php code example, so i understund that the php file in the server could be empty and it should work anyway.

  • if the code is fine, then should i ask to my hosting service about the Firewall or is there any other way to upload files using Javascript?.

thanks for reading!

0 Answers
Related