samedi 25 avril 2015

Ajax multiple file upload dont work


I'm usign this code to pass all file input by ajax. There are three input file in html code .But only the first file input be sent by ajax. how to fix this code? Where is my mistake?

$("#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 code:

<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 code:

//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;
            }
        }
    }


Aucun commentaire:

Enregistrer un commentaire