B
B
bdFregat2019-03-01 19:59:23
JavaScript
bdFregat, 2019-03-01 19:59:23

How to upload a file to the server using AJAX (CORS)?

There is a JS frontend and a PHP backend. They are located on different domains, communicate through the API
For normal data, we managed to set up CORS, everything goes ok.
The problem is with uploading files. The Ajax request itself succeeds, but the file does not arrive at the backend.

At the front

function upload(file) {
    var xhr = new XMLHttpRequest();
    xhr.onload = xhr.onerror = function (x) {
        console.log(x.target.response); // выводит [][][]
    };
    xhr.open("POST", "http://sitename", true);
    xhr.send(file);
 }
// висит на инпуте
function inputOnChange(e) {
    upload(e.target.files[0]);
}


On the backend
header('Access-Control-Allow-Origin: http://localhost:3000');
header('Access-Control-Allow-Headers: content-type');

echo json_encode($_GET);
echo json_encode($_POST);
echo json_encode($_FILES);


All arrays are empty. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bdFregat, 2019-03-02
@bdFregat

As always, it is worth formulating the question, as you yourself find the answer.
The FormData object helped me, everything worked.

V
vitalykostak, 2019-03-01
@vitalykostak

Sorry for not answering your question, but in this situation I would rather use the dropzone.js library. I didn’t know how to implement it either, but this library came to the rescue

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question