2015-04-24 3 views
0

Я использую этот код для передачи всех файлов ввода ajax. В html-коде есть три входных файла. Но только первый вход файла отправляется ajax. как исправить этот код? Где моя ошибка?Ajax многократная загрузка файла не работает

$("#add_order").click(function() { 

    //*****get data input 
    var formData = new FormData(); 
     formData.append('action', 'add_order'); 

    $.each($("input[type=file]"), function(i, obj) { 
     $.each(obj.files,function(j,file){ 
      alert(file.name); 
      formData.append('orderpic[]', file); 
     }); 
    }); 

    //ajax start and ajax complatet 
    ajax_loading(); 

    $.ajax({ 
     url: "includes/ajax/ajax.php", 
     data: formData, 
     processData: false, 
     contentType: false, 
     type: 'POST', 
     dataType:'json', 
     success: function(response){ 
      //load json data from server and output message  
      if(response.type == 'error'){ //load json data from server and output message  
       output = '<div class="alert alert-danger" style="margin-top:12px;">'+response.text+'</div>'; 
      }else{ 
       output = '<div class="alert alert-success" style="margin-top:12px;">'+response.text+'</div>'; 
       resetAllValues(); 
       setTimeout(function() { 
        $('#new-order').modal('hide'); 
       }, 1500); 
      } 
      $("#results").hide().html(output).fadeIn('slow').delay(800).fadeOut(); 
    });   
}); 

HTML код:

<input type="file" name="orderpic[]" id="orderpic" class="form-control"> 
<input type="file" name="orderpic[]" id="orderpic" class="form-control"> 
<input type="file" name="orderpic[]" id="orderpic" class="form-control"> 

PHP код:

//file settings 
    $files = array(); 
    for($i=0; $i<count($_FILES['orderpic']['name']); $i++) { 
     //Get the temp file path 
     $tmpFilePath = $_FILES['orderpic']['tmp_name'][$i]; 

     //Make sure we have a filepath 
     if ($tmpFilePath != "") { 
      //Setup our new file path 
      $time = time(); 
      $ext = pathinfo($_FILES['orderpic']['name'][$i], PATHINFO_EXTENSION); 
      $FilePath = $uploaddir . $time .'.'. $ext; 

      //Upload the file into the temp dir 
      if (move_uploaded_file($tmpFilePath, $FilePath)) { 
       $resizeObj = new resize($FilePath); 
       $resizeObj -> resizeImage(200, 350, 'portrait'); 
       $newFilePath = $uploaddir. "200_350_" .$time.'.'.$ext; 
       $resizeObj -> saveImage($newFilePath, 100); 
       unlink($FilePath); 
       $files[] = "200_350_" .$time.'.'.$ext; 
      } 
     } 
    } 
+0

Что вы имеете в виду под "не работает"? Есть ли ошибки? Вы проверили? –

+0

и как выглядит ваш php-код? Вы проверили сетевую вкладку инструментов разработчиков (обычно F12) и проверили запрос и посмотрели, действительно ли он отправляет все файлы или только один? –

+0

@PatrickEvans Я добавил PHP-код к вопросу. –

ответ

0

Вероятно, из-за не использования в $FilePath и $newFilePathbasename($_FILES['orderpic']['name'][$i]).

Попробуйте это:

for($i=0; $i<count($_FILES['orderpic']['name']); $i++) { 
     //Get the temp file path 
     $tmpFilePath = $_FILES['orderpic']['tmp_name'][$i]; 

     //Make sure we have a filepath 
     if ($tmpFilePath != "") { 
      //Setup our new file path 
      $time = time(); 
      $ext = pathinfo($_FILES['orderpic']['name'][$i], PATHINFO_EXTENSION); 
      //$FilePath = $uploaddir . $time .'.'. $ext; 
      $FilePath = $uploaddir . $time. basename($_FILES['orderpic']['name'][$i]); 

      //Upload the file into the temp dir 
      if(move_uploaded_file($tmpFilePath, $FilePath)){ 
       $resizeObj = new resize($FilePath); 
       $resizeObj -> resizeImage(200, 350, 'portrait'); 
       $newFilePath = $uploaddir ."200_350". $time. basename($_FILES['orderpic']['name'][$i]); 
       $resizeObj -> saveImage($newFilePath, 100); 
       unlink($FilePath); 
       $files[] = "200_350". $time. basename($_FILES['orderpic']['name'][$i]); 
      } 
     } 
    } 
+0

Спасибо. Этот код работает правильно. –

0

'ID' не может быть одинаковым для управления вводом. Измените его на что-то вроде показанного ниже в html, и оно должно работать.

<input type="file" name="orderpic[]" id="orderpic1" class="form-control"> 
    <input type="file" name="orderpic[]" id="orderpic2" class="form-control"> 
    <input type="file" name="orderpic[]" id="orderpic3" class="form-control"> 
+1

Хотя верно, что элементам нужны уникальные идентификаторы, так как OP не использует id для получения элементов, это не отвечает на вопрос. –

+0

Это не правильный ответ! –

Смежные вопросы