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

时间:2016-05-16 19:31:24

标签: php ajax serialization file-upload

你好朋友我试图通过这个表单的ajax上传数据和文件:

<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();
                }
            });
    });

的问题: 根据要求我没有收到服务器端php序列化的输入文件: i_files_1 如何将dile与发送的数据连接起来:

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

更新解决问题:

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

测试:

的print_r($ _ FILES);

3 个答案:

答案 0 :(得分:1)

在Google上进行一些搜索应该会为您提供Mozilla的优秀教程

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

然后您忘记添加到表单标记:enctype="multipart/form-data"以接受文件上传。

答案 1 :(得分:0)

由于空间不足,我无法在此处撰写/发布所有信息,但您可以前往http://moriche.ch/walter下载完整的解决方案......

没有标头指令文件仍然可以完美运行。以下是文件的内容:

    <?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);

答案 2 :(得分:0)

更新解决问题:

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