1

I want to upload a file in background using JavaScript and XMLHttpRequest but my page "upload.php" receive empty $_POST and $_FILES.

var formData = new FormData();
formData.append("file", file);
xhr.open("POST", "upload.php", true);
xhr.setRequestHeader('Cache-Control','no-cache');
xhr.setRequestHeader("Content-Type","multipart/form-data");     
xhr.send(formData);

I have try a lot a things in xhr.setRequestHeader() but nothings work.

  • @Machavity Since this question doesn't mention [tag:jquery] or appear to use it, I wouldn't count this as a duplicate of that particular Q&A, at least. – Jonathan Lonowski Aug 25 '14 at 00:20
  • What is the value of `file`, in this case? Also, have you tried without setting the headers manually? `.send()` will already set some headers just from being given `FormData`. – Jonathan Lonowski Aug 25 '14 at 00:24
  • `file` is a file object from an input `` I just tried withouth setting the header, the result is the same. – kiran morin Aug 25 '14 at 00:34
  • the file name is missing, not sure if that matters... – dandavis Aug 25 '14 at 01:30
  • 1
    Iin the header settings ? I have tried but it doesn't work too – kiran morin Aug 25 '14 at 10:22
  • xhr.send only works when the parameter is a File object, not a FormData think. So I use jquery $.ajax, which allows post form data and files at the same time – Mitoxys May 14 '18 at 03:34

0 Answers0