doutou3725
2016-05-16 19:31
浏览 55

使用Ajax PHP formData上传文件和数据提交XHR

hello friend i am trying to upload data and files at some time via ajax with this form:

<form id="formarea" class="form-horizontal" name="desk">
<input type="text" class="form-control " name="i_txt_2">
<input type="number" class="form-control " name="i_txt_3" required>
<input type="file" name='i_files_1'>
<input type="file" name='i_files_2'>
<input type="file" name='i_files_3'>
</form>

Ajax:

$('[id^="save"]').on("click", function (event, xhr, settings) {
        var id = event.target.id;
        var name = $("#formarea").attr("name");
        $.ajax({
            type:"POST",url:"index.php",data:$("#formarea").serialize()+ '&idprocess=' + id + '&idform=' + name,
                error: function(xhr,status,error){console.log(error)},
                success:    function(response) {
                    $("#areasmg").html(response);
                    $("#MsgArea").removeClass("").addClass("alert alert-warning alert-dismissable");
                    $("#MsgArea").show();
                }
            });
    });

issues: on request i am not received in server side php serialized of Input File: i_files_1 how can i concatenate the dile to data sent:

data:$("#formarea").serialize()+ '&idprocess=' + id + '&idform=' + name + '&Files' + files[]Serialized ,

UPDATE Problem Solved:

//If you have button to submit Form
$('[id^="BTN-"]').on("click", function (event, xhr, settings) {
    var id = event.target.id; //get id buton to filter if you like get control over the button clicked
    var req = 0;
    $('#formarea *').filter(':input').each(function(){ //filter all requiered input field
        if($(this).val() === "" && $(this).attr('required')){req ++;}
    });
    if(req == 0){
        var name = $("#formarea").attr("name"); //get name of form if you like get control over the form submited
        //window.WindowsWait();
        var input1 = $("<input>").attr("type", "hidden").attr("name", "idprocess").val(id); //Adding field for more controls if you neet handle from PHP
        var input2 = $("<input>").attr("type", "hidden").attr("name", "idform").val(name); //Adding field for more controls if you neet handle from PHP
        $('#formarea').append($(input1)); //inserting on Html
        $('#formarea').append($(input2)); //inserting on Html
        event.preventDefault(); //prevent default submit
        //get form an serialize data with FormData
        var $form       = $("#formarea"), 
            formData    = new FormData(),
            params      = $form.serializeArray();               
        var inputs = $("input[type=file]");
        //Get all Input tipe Files
        $.each(inputs, function (obj, v) {
            // Prefix the name of uploaded files with "uploadedFiles-"
            // Of course, you can change it to any string
            var file = v.files[0];
            var name = $(v).attr("name");//you can work with the name
            formData.append(name, file);
        });
        // Add all params to the formData
        $.each(params, function(i, val) {
            formData.append(val.name, val.value);
        });
        //performing the submit
        $.ajax({
            url: $form.attr('action'),
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            error: function(xhr,status,error){console.log(error)},
            success:    function(response) {
                alert(response);//print response server
            }
        });

    }else{
        alert("Error: You must fill all field, there " + req + " Empty Fields.");//handle Error Empty Fields
    }
});

Test:

print_r($_FILES);

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douqu2712 2016-05-17 00:19
    已采纳

    UPDATE Problem Solved:

    //If you have button to submit Form
    $('[id^="BTN-"]').on("click", function (event, xhr, settings) {
        var id = event.target.id; //get id buton to filter if you like get control over the button clicked
        var req = 0;
        $('#formarea *').filter(':input').each(function(){ //filter all requiered input field
            if($(this).val() === "" && $(this).attr('required')){req ++;}
        });
        if(req == 0){
            var name = $("#formarea").attr("name"); //get name of form if you like get control over the form submited
            //window.WindowsWait();
            var input1 = $("<input>").attr("type", "hidden").attr("name", "idprocess").val(id); //Adding field for more controls if you neet handle from PHP
            var input2 = $("<input>").attr("type", "hidden").attr("name", "idform").val(name); //Adding field for more controls if you neet handle from PHP
            $('#formarea').append($(input1)); //inserting on Html
            $('#formarea').append($(input2)); //inserting on Html
            event.preventDefault(); //prevent default submit
            //get form an serialize data with FormData
            var $form       = $("#formarea"), 
                formData    = new FormData(),
                params      = $form.serializeArray();               
            var inputs = $("input[type=file]");
            //Get all Input tipe Files
            $.each(inputs, function (obj, v) {
                // Prefix the name of uploaded files with "uploadedFiles-"
                // Of course, you can change it to any string
                var file = v.files[0];
                var name = $(v).attr("name");//you can work with the name
                formData.append(name, file);
            });
            // Add all params to the formData
            $.each(params, function(i, val) {
                formData.append(val.name, val.value);
            });
            //performing the submit
            $.ajax({
                url: $form.attr('action'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                error: function(xhr,status,error){console.log(error)},
                success:    function(response) {
                    alert(response);//print response server
                }
            });
    
        }else{
            alert("Error: You must fill all field, there " + req + " Empty Fields.");//handle Error Empty Fields
        }
    });
    
    打赏 评论
  • dongshenling6585 2016-05-16 19:50

    A little search on Google should give you a excellent tutorial by Mozilla

    https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

    Then you forgot to add to your form tag : enctype="multipart/form-data" to accept file uploads.

    打赏 评论
  • duanfu9523 2016-05-16 20:41

    I cannot write/post all the information here for want of space but you can go to http://moriche.ch/walter to download a fully working solution...

    Without the Header Directive The File will still work perfectly. Here is the content of the File:

        <?php
            // file-processor.php
            // HEADER HAS BEEN REMOVED, YET IT WILL STILL WORK...
    
            // HERE YOU CAN ACCESS ALL THE FIELDS THAT ARE CONTAINED IN THE FORM.
            // EVERY ONE OF THEM: FROM NUMBER FIELD TO TEXT AREA, ETC ;-)
            $text2          = isset($_POST['text2']) ? htmlspecialchars(trim($_POST['text2'])) : null;
            $text3          = isset($_POST['text3']) ? htmlspecialchars(trim($_POST['text3'])) : null;
            $arrStatus      = array();
            $arrResponse    = array();
    
            if(isset($_FILES['i_files_1'])){
                $fileData               = $_FILES['i_files_1'];
                $arrStatus["i_files_1"] = uploadFile($fileData);
            }
    
            if(isset($_FILES['i_files_2'])){
                $fileData               = $_FILES['i_files_2'];
                $arrStatus["i_files_2"] = uploadFile($fileData);
            }
    
            if(isset($_FILES['i_files_3'])){
                $fileData               = $_FILES['i_files_3'];
                $arrStatus["i_files_3"] = uploadFile($fileData);
            }
    
            function uploadFile($fileData, $uploadDir = __DIR__ . "/img"){
                $flTName    = $fileData['tmp_name'];
                $flName     = $fileData['name'];
                $flType     = $fileData['type'];
                $flSize     = $fileData['size'];
                $flErr      = $fileData['error'];
    
                $info       = new SplFileInfo($flName);
                $ext        = $info->getExtension();
    
                if(!is_dir($uploadDir)){
                    mkdir($uploadDir, 0777, true);
                }
    
                $pixDst     = $uploadDir . "/uploaded_pix_" . generateRandomString() . "." . $ext;
                return move_uploaded_file($flTName, $pixDst);
            }
    
    
            foreach($arrStatus as $fileKey=>$boolStatus){
                if($boolStatus){
                    $arrResponse[$fileKey] = $fileKey . " was successfully uploaded...";
                }else{
                    $arrResponse[$fileKey] = "Error: could not upload \"{$fileKey}\"";
                }
            }
    
            function generateRandomString($length = 8) {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $randomString = '';
                for ($i = 0; $i < $length; $i++) {
                    $randomString .= $characters[rand(0, strlen($characters) - 1)];
                }
                return $randomString;
            }
    
    
            die( json_encode($arrResponse) );
    

    JAVASCRIPT

        (function ($) {
            $(document).ready(function(e) {
                var text2               = $("input[name=i_txt_2]");
                var text3               = $("input[name=i_txt_3]");
                var files               = $("input[type=file]");
                var theForm             = $("#formarea");
                var formAction          = theForm.attr("action");
    
                files.each(function(dt, dom){
                    var target = $(this);
                    target.change(function(evt) {
                        evt.preventDefault();
                        var dis     = $(this);
                        var dis_val = dis.val();
    
                        // HERE YOU CAN JUST ADD THE FILE TYPES YOU WANT TO SUPPORT
                        // LIKE MP3, MP4, PDF, ETC...
                        if (dis_val && /(\.)(jpg|jpeg|png|gif|bmp)$/.test(dis_val)) {
                            // THE RIGHT FILES WERE UPLOADED SO DO NOTHING;
                        } else {
                            alert("Only Images in with the Format: (JPG, JPEG, PNG, GIF, BMP) are allowed.");
                            dis.val(null);
                            return false;
                        }
                    });
                });
    
    
                theForm.submit(function (evt) {
                    var $this = $(this);
                    evt.preventDefault();
    
                    $this.attr("action", formAction).ajaxSubmit({
                        dataType:       "HTML",
                        success:        confirmFileUpload,
                        cache:          false
                    });
                });
    
                function confirmFileUpload(data){
                    console.log(data);
                    console.log("File was uploaded and the World is fine again...");
                }
            });
        })(jQuery);
    
    打赏 评论

相关推荐 更多相似问题