【问题标题】:form data upload multiple files through ajax together with text fields表单数据通过ajax连同文本字段一起上传多个文件
【发布时间】:2017-04-05 19:08:14
【问题描述】:

大家好,

我有一个表单,里面有多个字段。此外,表单正在通过使用 ajax 的表单数据方法提交到 php 文件。

以下是提交表单数据的javascript代码。

$(".update").click(function(){

        $.ajax({
        url: 'post_reply.php',
        type: 'POST',
        contentType:false,
        processData: false,
        data: function(){
            var data = new FormData();
            data.append('image',$('#picture').get(0).files[0]);
            data.append('body' , $('#body').val());
            data.append('uid', $('#uid').val());
            return data;
        }(),
            success: function(result) {
            alert(result);
            },
        error: function(xhr, result, errorThrown){
            alert('Request failed.');
        }
        });
        $('#picture').val('');
$('#body').val('');
});

而且,下面是实际的形式:

<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update  />

这种形式和 javascript 可以正常工作。但是,我试图能够使用这个单一的 type=file 字段属性将多个文件上传到 php 文件。就像现在一样,一次只能处理一个文件。如何调整表单和 javascript 代码以处理多个文件上传?

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: javascript php ajax forms


    【解决方案1】:

    这里是你可以访问的ajax、html和php global。让我知道它是否适合你。

    // Updated part
    jQuery.each(jQuery('#file')[0].files, function(i, file) {
        data.append('file-'+i, file);
    });
    
    // Full Ajax request
    $(".update").click(function(e) {
        // Stops the form from reloading
        e.preventDefault();
    
            $.ajax({
            url: 'post_reply.php',
            type: 'POST',
            contentType:false,
            processData: false,
            data: function(){
                var data = new FormData();
                jQuery.each(jQuery('#file')[0].files, function(i, file) {
                    data.append('file-'+i, file);
                });
                data.append('body' , $('#body').val());
                data.append('uid', $('#uid').val());
                return data;
            }(),
                success: function(result) {
                alert(result);
                },
            error: function(xhr, result, errorThrown){
                alert('Request failed.');
            }
            });
            $('#picture').val('');
    $('#body').val('');
    });
    

    更新的 HTML:

    <form enctype="multipart/form-data" method="post">
      <input id="file" name="file[]" type="file"  multiple/>
      <input class="update" type="submit" />
    </form>
    

    现在,在 PHP 中,您应该可以访问您的文件了:

    // i.e.    
    $_FILES['file-0']
    

    【讨论】:

    • 实际上,它似乎可以工作,但有一个小问题。当我从计算机中选择文件,然后按下提交按钮时……警报功能可以正常工作,但仍然,浏览器似乎重新加载……或显示正在旋转的加载图标。我希望在单击提交按钮时将文件发送到 php 文件并显示警报框。当我按下浏览器的刷新按钮时,它不会询问我是否要重新提交信息。目前,浏览器询问我是否要重新提交.....如何解决? ..单击按钮时,我根本不想加载浏览器。
    • 我已经更新了答案,现在应该可以了。您需要像这样将事件参数添加到您的函数中:function(e) 并使用 e.preventDefault(); 来防止重新加载表单。查看更新的答案。
    • @loelsonk 我按照您的链接保存浏览的多个文件。我从我的系统中选择了多个文件,并在下面的函数中显示了一个文本:jQuery.each(jQuery('#file')[0].files, function(i, file) { data.append('file-'+我,文件);});但它只警告过一次。我只能保存最后浏览的文件。我怎样才能保存所有浏览的文件。
    【解决方案2】:

    这是另一种方式。

    假设你的 HTML 是这样的:

    <form id="theform">
        <textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
        <!-- note the use of [] and multiple -->
        <input type="file" name="image[]" id="picture" multiple>
        <input name="update" value="Send" type="submit" class="update" id="update">
    </form>
    

    你可以这样做

    $("#theform").submit(function(e){
        // prevent the form from submitting
        e.preventDefault();
        $.ajax({
            url: 'post_reply.php',
            type: 'POST',
            contentType:false,
            processData: false,
            // pass the form in the FormData constructor to send all the data inside the form
            data: new FormData(this),
            success: function(result) {
                alert(result);
            },
            error: function(xhr, result, errorThrown){
                alert('Request failed.');
            }
        });
        $('#picture').val('');
        $('#body').val('');
    });
    

    因为我们使用了[],所以您将在 PHP 中以数组的形式访问文件。

    <?php
    print_r($_POST);
    print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
    ?>
    

    更多信息:

    【讨论】:

    • 我测试了代码。我有一个 php 文件,可以检测何时提交一个或多个文件。这是问题:当我选择 0 个文件时,php 文件说它有一个文件。当我选择 1 个文件时,它说它收到了一个文件。当我选择两个文件时,单击提交按钮后,页面会刷新并清除表单数据。有什么问题?
    • 这是因为该按钮是表单中的type="submit" 按钮——这意味着,默认情况下,如果您单击该按钮,它将提交表单并重新加载页面。你想防止这种情况发生。检查我的编辑,尤其是 HTML 和 JS 代码。请注意,我将onsubmit 事件处理程序附加到表单,而不是onclick 事件处理程序到按钮。
    猜你喜欢
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多