1

(as asked by so to clarify why my question is not duplicated of suggested post )

IMHO My question is not duplicate to that question since

  1. I am suing JavaScript and Ajax which linked question does not
  2. though I have tried solution of that post which doesn't worked

I am using ajax and to make ajax request I am using javaScript

HTML

<input id="file" type="file" name="our-file" />
<input type="button" value="Upload" id="upload-button"   /> 

Js

var inputFile = document.getElementById("file"),
    uploadButton = document.getElementById("upload-button");

uploadButton.onclick = function () {
    console.log(inputFile.files[0])

    var file = inputFile.files[0];

    var httpRequest = new XMLHttpRequest();

    httpRequest.onreadystatechange = stateHandler;


    httpRequest.open("POST", "upload.php", true);
    httpRequest.setRequestHeader("X-File-Name", file.name);
    httpRequest.send(file)


    function stateHandler() {
        var status = {
            "httpRequest ready state": httpRequest.readyState,
            "status": httpRequest.status,
            "httpRequest responseText":httpRequest.responseText
        };
        console.log(status);
        console.log(httpRequest.responseText);
    }
}

now when I try to get uploaded file via $_FILES I get empty array but $_SERVER have complete file information, is it because I have only sent header not file itself ?

screeshot of my output with $_SERVER https://i.stack.imgur.com/1GMdh.png
screen shot of my output with $_FILES https://i.stack.imgur.com/IECUt.png

thanks and I don't want jquery suggestion (I think its good to know language before framework developed by it :)

Richerd fuld
  • 364
  • 1
  • 10
  • 23
  • Does your form have `enctype="multipart/form-data"`? Have you configured your php.ini file to have `file_uploads = On;`? – ʰᵈˑ Mar 11 '15 at 09:18
  • yes I have checked and form have `enctype="multipart/form-data"` and file_upload is on too – Richerd fuld Mar 11 '15 at 09:19
  • Did you then restart Apache? Please check http://stackoverflow.com/a/3587158/3000179 and see if that can help – ʰᵈˑ Mar 11 '15 at 09:19
  • possible duplicate of [Why would $\_FILES be empty when uploading files to PHP?](http://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php) – ʰᵈˑ Mar 11 '15 at 09:20
  • @ʰᵈˑ I am still getting empty in `$_FILES` . I have tried solution in linked question – Richerd fuld Mar 11 '15 at 09:24

1 Answers1

2

You are sending raw file data. You aren't sending a multipart/form-data encoded request, so it won't be processed as regular form data (so $_FILES and $_POST won't be populated).

Create a form data object.

var formData = new FormData();

Put the file information in that:

formData.append("myFile", inputFile.files[0]);

Send that:

request.send(formData);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335