There is a form. Most of the data from it is collected and processed in PHP, except for one input.

<div id="drop-zone"> <p>Перетащите файлы сюда...</p> <div id="clickHere">или нажмите здесь.. <i class="fa fa-upload"></i> <input type="file" name="file[]" id="files" multiple /> </div> <div id='filename'></div> </div> 

I collect all this into an array (if necessary - I can show the code), I send the array as follows:

 var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://zayavlenie.com.ua/mail-dev.php', true); // The rest of the code will go here... // Set up a handler for when the request finishes. xhr.onload = function() { if (xhr.status === 200) { // File(s) uploaded. uploadButton.innerHTML = 'Отправка'; } else { alert('An error occurred!'); } }; console.log(formData); console.log(finalFiles); xhr.send(finalFiles); if (xhr.status != 200) { // обработать ошибку alert(xhr.status + ': ' + xhr.statusText); // пример вывода: 404: Not Found } else { alert(xhr.responseText); // responseText -- текст ответа. } } 

On the server side, I try to listen to everything that comes in this way:

 <? header('Access-Control-Allow-Origin: *'); $post = $_POST; var_dump($post); echo('<hr>'); $req = $_REQUEST; var_dump($req); echo('<hr>'); 

At the output, I receive data from fomry that are processed by the php script, but not the value of the field input type="file" The $ _FILES array returns the following

 array(1) { ["file"]=> array(5) { ["name"]=> array(1) { [0]=> string(0) "" } ["type"]=> array(1) { [0]=> string(0) "" } ["tmp_name"]=> array(1) { [0]=> string(0) "" } ["error"]=> array(1) { [0]=> int(4) } ["size"]=> array(1) { [0]=> int(0) } } } string(0) "" Warning: fopen(): Filename cannot be empty in /var/www/zayavlenie/zayavlenie.com.ua/mail-dev.php on line 227 Warning: fread() expects parameter 1 to be resource, boolean given in /var/www/zayavlenie/zayavlenie.com.ua/mail-dev.php on line 228 Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/zayavlenie/zayavlenie.com.ua/mail-dev.php on line 229 

How to send data correctly using xhr.send ()

  • the question should be one - Ipatiev
  • @ Ipatiev I have one question: How to correctly form and send data via xhr.send () and process it in php with the mail () function? - Anton
  • "I have one question: question number 1 and question number 2" :))) - Ipatyev
  • @ Ipatiev)) Ok, please answer me the first question, how to do it right? - Anton
  • I think it would be right not to do this - Ipatiev

1 answer 1

  1. On the client side, files should be sent through the FormData object, which means that the files need to be converted, for example, like this:

     var inputElem = document.getElementById('files'); var files = inputElem.files; var data = new FormData(); Array.from(files).forEach(file => data.append(file.name, file)); 

Checking the presence of elements in FormData is carried out by the method has ( data.has(NAME) ), and getting get ( data.get(NAME) ).

1.2 Data is Content-Type : multipart/form-data via the Content-Type : multipart/form-data (default).

 var async = true; var xhr = new XMLHttpRequest(); xhr.open('POST', URL_NAME, async); xhr.setRequestHeader("Content-Type", "multipart/form-data"); //этот header добавляется по умолчанию xhr.send(files); 

Example.

 var URL_NAME = 'http://zayavlenie.com.ua/mail-dev.php'; var async = true; var inputElem = document.getElementById('files'); var ip1 = document.getElementById('ip1'); var ip2 = document.getElementById('ip2'); var data = new FormData(); function collectFiles() { var files = inputElem.files; Array.from(files).forEach(file => data.append(file.name, file)); } function collectInputs() { data.append('ip1', ip1.value); data.append('ip2', ip2.value); } function send() { var xhr = new XMLHttpRequest(); xhr.open('POST', URL_NAME, async); xhr.send(data); } function submit() { collectFiles(); collectInputs(); send(); } 
 <div class="another-inputs"> <input id="ip1" type="text"/> <input id="ip2" type="text"/> </div> <div id="drop-zone"> <p>Перетащите файлы сюда...</p> <div id="clickHere">или нажмите здесь.. <i class="fa fa-upload"></i> <input type="file" name="file[]" id="files" multiple /> </div> <div id='filename'></div> <button onClick="submit()">SEND</button> </div> 

  1. On the server , file information can be viewed in the $ _FILES global array. C mechanism for downloading files using the POST method can be found here . In fact, it all comes down to getting the file name ( basename ), and moving it to the existing directory ( move_uploaded_file )

In your case the mail-dev.php file will be approximately the same.

 $uploaddir = '/var/www/uploads/'; foreach ($_FILES as $key => $value) { $uploadfile = $uploaddir . basename(value['name']); move_uploaded_file(value['tmp_name'], $uploadfile); //... + обработка ошибок } 

So, to send the file you need:
- collect files from the form / input;
- convert the collected files to the FormData object;
- send Ajax multipart / form-data;
- on the server (mail-dev.php) process files.

  • one
    It does not take into account the most important question of the author: he sends the files separately from the entire form, and waits for them in the same processor. - Ipatiev
  • @ Ipatiev so he, as I understood the Ajax sends, gathering them together - Kostiantyn Okhotnyk
  • one
    @ Anton is possible, why not? Edited an example. Take a closer look at it. Added random input. They are also added to the FormData object. - Kostiantyn Okhotnyk
  • one
    @ Anton, the collectFiles function adds files, the collectInputs function adds information on other inputs. All this is added to the resulting data object (ifo by input + files). And this data is sent to the server - Kostiantyn Okhotnyk
  • one
    @ Anton, by the way, the xhr.setRequestHeader ("Content-Type", "multipart / form-data") header is not needed here; You transfer not only files - Kostiantyn Okhotnyk