2016-06-08 24 views
10

Sto usando JQuery per pubblicare i dati dei moduli e ho aggiunto questo nella mia funzione per permettere di inviare/caricare i file:JQuery multipart/dati ajax messaggio

mimeType:"multipart/form-data", 

sto chiamando nel mio modulo HTML qui :

<form id="form1" method="post" action="/tickets/record?type=<?php echo $_GET["type"]; ?>&seq=<?php echo $_GET["seq"]; ?>" enctype="multipart/form-data" onsubmit="post_form('#form1');"> 

e cercando di gestire gli allegati in PHP con:

$attachment_array = array();  
foreach($_FILES['ticket_update_files']['name'] as $key => $value) { 
    if(!$_FILES['ticket_update_files']['error'][$key]) { 

    } 
} 

ma la sua non recognisin g che tutti i file che sono stati selezionati.

La mia funzione completa jquery è:

function post_form(form_id, type, redir_url, loading_modal) { 
    type = type || ''; 
    redir_url = redir_url || ''; 
    loading_modal = loading_modal || ''; 

    $(form_id).submit(function(e) { 
     var formObj = $(this); 
     var formURL = formObj.attr("action"); 
     var formData = new FormData(this); 

     CheckRequired(e); 

     if(loading_modal === '1') { } else { 
      LoadModalBody('<h2 align="center">Loading...</h3><p align="center"><i class="fa fa-refresh fa-spin fa-5x"></i></p>', 'Loading'); 
     } 

     $.ajax({ 
      url : '/section' + formURL, 
      type: "POST", 
      data : formData, 
      mimeType:"multipart/form-data", 
      contentType: false, 
      cache: false, 
      processData:false, 
      success:function(data, textStatus, jqXHR) { 
       //alert(type); 
       if(type === 'modal') { 
        if(redir_url === '') { 
         LoadModal('/section' + formURL, ''); 
        } else { 
         LoadModal('/section' + redir_url, ''); 
        } 
       } else if(type === 'reload') { 
        if(redir_url === '') { 
         location.reload(); 
        } else { 
         OpenPage(redir_url); 
        } 
       } else { 
        //close the loading modal 
        if(loading_modal === '1') { } else { 
         CloseModal(); 
        } 
        //location.reload(); 
        //$("body").html(data); 
       } 
      }, 
      error: function(jqXHR, textStatus, errorThrown) { 
       //if fails 
      } 
     }); 
     return false; 
     e.preventDefault(); 
    }); 
} 
+1

Guardate [questa domanda] (http://stackoverflow.com/questions/10899384/uploading-both-data-and-files -in-one-form-using-ajax) forse può aiutarti. Guarda la risposta corretta, come ha formato l'AJAX. – matiaslauriti

risposta

1

tenta di aggiungere ogni file per oggetto formdata manualmente. Ecco come

HTML:

<form id="my_form" method="post" action="" enctype="multipart/form-data"> 
    <input type="file" id="my_files" multiple> 
    <input type="submit"> 
</form> 

JS:

$("#my_form").submit(function(e) { 
    e.preventDefault(); 
    var data = new FormData(); 
    $.each($('#my_files')[0].files, function(i, file) { 
     data.append('file[]', file); 
    }); 
    $.ajax({ 
     url: 'http://162.243.221.224/multipart/upload.php', // I will keep this script alive for few weeks 
     data: data, 
     cache: false, 
     contentType: false, 
     processData: false, 
     // mimeType:"multipart/form-data", 
     type: 'POST', 
     dataType: "text", 
     success: function(data){ 
      alert(data); 
     }, 
     error: function(data){ 
      alert(data); 
     } 
    }); 
    return false;   
}); 

PHP:

<?php 
    print_r($_FILES['file']['name']); 

hanno testato in Firefox 47,0 con l'ultima jQuery. Ha funzionato per me (senza specificare mimeType in ajax e l'attributo action nel tag form).

4

Da utilizzare per l'invio di Jquery multipart/form-data.

$(document).ready(function (e) { 
    $("#formid").on('submit', (function (e) { 
     e.preventDefault(); 
     $("#message").empty(); 
     $('#loading').show(); 
     $.ajax({ 
      url: "ajax_php_villa_file.php", // Url to which the request is send 
      type: "POST",    // Type of request to be send, called as method 
      data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values) 
      contentType: false,  // The content type used when sending data to the server. 
      cache: false,    // To unable request pages to be cached 
      processData: false, 
      beforeSend: function() { 
       $('.loader-img').show(); 
      },  // To send DOMDocument or non processed data file it is set to false 
      success: function (data) // A function to be called if request succeeds 
      { 
       $('.loader-img').hide(); 
       if (data.trim() != "") 
        $("#imresss").html(data); 
      } 
     }); 
    })); 
}); 
0

Ecco come si fa:

function post_form(form_id, type, redir_url, loading_modal) { 
    type = type || ''; 
    redir_url = redir_url || ''; 
    loading_modal = loading_modal || ''; 

    $(form_id).submit(function(e) { 
     var formObj = $(this); 
     var formURL = formObj.attr("action"); 
     var formData = new FormData; 
     //File Field 
     var regexp = /^[^[\]]+/, 
      fileInput = $(form_id+' input[type="file"]'), //If form doesn't work try to select the file input by ID here. ex: fileInput = $("#myFileInputHere"); 
      fileInputName = regexp.exec(fileInput.attr('name')); 
      $.each($(fileInput)[0].files,function(i,file) { 
       formData.append(fileInputName, file); //Add file to form 
      }); 

     CheckRequired(e); 

     if(loading_modal === '1') { } else { 
      LoadModalBody('<h2 align="center">Loading...</h3><p align="center"><i class="fa fa-refresh fa-spin fa-5x"></i></p>', 'Loading'); 
     } 

     $.ajax({ 
      url : '/section' + formURL, 
      type: "POST", 
      data : formData, 
      cache: false, 
      contentType: false, 
      processData: false, 
      success:function(data, textStatus, jqXHR) { 
       //alert(type); 
       if(type === 'modal') { 
        if(redir_url === '') { 
         LoadModal('/section' + formURL, ''); 
        } else { 
         LoadModal('/section' + redir_url, ''); 
        } 
       } else if(type === 'reload') { 
        if(redir_url === '') { 
         location.reload(); 
        } else { 
         OpenPage(redir_url); 
        } 
       } else { 
        //close the loading modal 
        if(loading_modal === '1') { } else { 
         CloseModal(); 
        } 
        //location.reload(); 
        //$("body").html(data); 
       } 
      }, 
      xhr: function(){ 
       // get the native XmlHttpRequest object 
       var xhr = $.ajaxSettings.xhr() ; 
       // set the onprogress event handler 
       xhr.upload.onprogress = function(evt){ 
       var perc = Math.round(evt.loaded/evt.total*100); 
       console.log(perc+'% Uploading...'); 
       } ; 
       // set the onload event handler 
       xhr.upload.onload = function(){ 
       console.log('Uploaded!'); 
       } ; 
       // return the customized object 
       return xhr ; 
       } , 
      error: function(jqXHR, textStatus, errorThrown) { 
       //if fails 
      } 
     }); 
     return false; 
     e.preventDefault(); 
    }); 
} 
+0

La tua soluzione rende troppo complicato tutto e passerà solo i campi di input del tipo di file. Si può semplicemente fare 'formData = new FormData (this)' (senza fare alcuna regex o appending) che passerà tutti i campi all'interno del form. – Mikey