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?

Itsmeromka
  • 3,621
  • 9
  • 46
  • 79

1 Answers1

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

Ofir Baruch
  • 10,323
  • 2
  • 26
  • 39