How to upload a file using pure vanilla javascript and php?

I have an existing html form that uploads a file to the server as soon as the user selects the image file.

I did something like this.

//html code
<input type="file" id="photo" name="photo" accept="image/*" />
// the usual html stuff

document.getElementById('photo').addEventListener("change",uploadImage);
function uploadImage()
{
    var xhr = new XMLHttpRequest();

    xhr.open("POST","/upload.php",true);    
    xhr.setRequestHeader("Content-type","image");

    var file = document.getElementById('photo').files[0];
    if(file)
    {
        var formdata = new FormData();
        formdata.append("pic",file);
        xhr.send(formdata);
    }
    xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200)
    {
             //some code
    }
};
}

But in my php file, I cannot access this downloaded file. The array $_POSTseems empty. I did print_rfor $_POSTand gave Array(). What am I doing wrong?

+4
source share
1 answer

You use FormDataone that works very exactly the same as the regular form.

, PHP $_POST, $_FILES, . .

$_FILES, multipart/form-data, FormData, XMLHttpRequest, , , $_FILES . xhr.setRequestHeader("Content-type","image");, XHR , - -

xhr.setRequestHeader("Content-type","multipart/form-data");

fooobar.com/questions/998551/...

+4

Source: https://habr.com/ru/post/1622364/


All Articles