K
K
kn1ght_t2016-02-10 19:32:06
PHP
kn1ght_t, 2016-02-10 19:32:06

How to accept files sent by ajax via formData on the server side?

given a form with an input with the multiple attribute:

<form>
          <input  type="file" name="file" multiple="multiple">
</form>


I send it with Ajax via formData:
$('form').submit(function(){
    $.ajax({
      type: "POST",
      url: "phpmailer/mail.php",
      data: new FormData( this ),
      processData: false,
      contentType: false,
      success: function() {

      }
  return false;
});


on the server side I use the phpmailer library (this way it only works for one or the first file submitted via the form):
<?php
require_once('class.phpmailer.php');

$email1 = new PHPMailer();
$email1->CharSet = 'UTF-8';
$email1->IsHTML(true);
$email1->From      = '[email protected]';
$email1->FromName  = 'Имя проекта';
$email1->Subject   = "Тема (Имя проекта): ".$form_name;
$email1->Body      = $bodytext1;
$email1->AddAddress( '[email protected]' );

if (isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK) {
  $email1->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
}
?>


how to make the server accept several files from one input at once?
this option doesn't work:
foreach ($_FILES['file'] as $file) {
  if (isset($file) && $file['error'] == UPLOAD_ERR_OK) {
    $email1->AddAttachment($file['tmp_name'], $file['name']);
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2016-02-10
@kn1ght_t

print_r($_FILES);
and everything will become clear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question