Answer the question
In order to leave comments, you need to log in
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]);
}
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);
Answer the question
In order to leave comments, you need to log in
As always, it is worth formulating the question, as you yourself find the answer.
The FormData object helped me, everything worked.
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 questionAsk a Question
731 491 924 answers to any question