简体   繁体   English

jQuery Multipart / Data Ajax发布

[英]JQuery multipart/data ajax post

I am using JQuery to post form data and I have added this into my function to allow it to post / upload files: 我正在使用JQuery发布表单数据,并将其添加到我的函数中以允许其发布/上传文件:

mimeType:"multipart/form-data",

I am calling it in my HTML form here: 我在这里以我的HTML形式调用它:

<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');">

and trying to handle the attachments in PHP with: 并尝试通过以下方式处理PHP中的附件:

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

    } 
}

but its not recognising that any files that have been selected. 但无法识别已选择的任何文件。

My full jquery function is: 我完整的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();
    });
}

Use this for Jquery multipart/form-data submission. 使用它进行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);
            }
        });
    }));
});

Try to add each file to FormData object manually. 尝试将每个文件手动添加到FormData对象。 Here is how. 这是怎么回事。

HTML: HTML:

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

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

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

Have tested it in Firefox 47.0 with latest jquery. 已使用最新的jquery在Firefox 47.0中对其进行了测试。 Worked for me (without specifying mimeType in ajax and action attribute in form tag). 为我工作(在ajax中未指定mimeType,在表单标签中未指定action属性)。

This is how you do it: 这是您的操作方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM