0

I'am trying to upload a file from js to php like this

        var formData = new FormData();
        formData.append('file', uploadedFile);

        var request = new XMLHttpRequest();

        request.onload = function () {
            if (request.readyState == 4) {
                var response = JSON.parse(request.responseText);
                console.log(response);
            }
        };

        request.open('POST', settings.restUri + 'files');
        request.setRequestHeader("Content-Type", "multipart/form-data");
        request.send(formData);

As a result my request payload looks like this

            ------WebKitFormBoundaryRl1Q67A1DDBjvKCU
            Content-Disposition: form-data; name="file"; filename="user.svg"

            Content-Type: image/svg+xml


            ------WebKitFormBoundaryRl1Q67A1DDBjvKCU--

but $_FILES variable is empty on PHP side, what's wrong?

4
  • 2
    Try to comment out this line: request.setRequestHeader("Content-Type", "multipart/form-data"); Commented Feb 1, 2017 at 12:33
  • It works, but why? (add like a comment, i ll mark an answer) Commented Feb 1, 2017 at 12:34
  • new FormData is multipart/form-data if i am not mistaken. Commented Feb 1, 2017 at 12:37
  • Added and added the reason. please consider accepting my answer if it helped you. Commented Feb 1, 2017 at 12:42

1 Answer 1

1

Remove this line:

request.setRequestHeader("Content-Type", "multipart/form-data");

The reason is emphasised in bold.

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to multipart/form-data.

Source

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.