ajax - 如何上传多个文件

时间:2015-09-13 06:43:58

标签: php jquery ajax

我被困住了,需要你的帮助 - 我设计了一个简单的表单,允许用户将评论文本和文件上传到服务器。提交表单后,文件上载过程将在“upload.php”文件中处理。它仅适用于上传1个文件。

我希望我的脚本能够使用AJAX上传多个文件。

这是我到目前为止所做的 -

HTML(部分内容):

<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />
<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />
<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />

JS

$(function() {
    $(document).on('submit','form',function(e) {
        e.preventDefault(); 

    var $form = $(this);
    var file_data = $form.find('.file-field').prop('files')[0];   
    var form_data = new FormData();       
    form_data.append('act', act);
    form_data.append('comment[text]',  $form.find('.comment-field').val());   
    form_data.append('comment[pageName]',  $form.find('.pagename-field').val());   

    form_data.append('file[]', file_data);



    $.ajax({
           type: "POST",
           url: "ajax/addComment.php",

           dataType: 'text',  
           cache: false,
           contentType: false,
           processData: false,  
           async: false,
           data: form_data,
           success: function(data)
           {
                $("#loader").hide();
                $('#commentsBox'+$form.find('.refid-field').val()).prepend(data);
                 $("form").reset(); 

           }

         });

    return false; 

    });
});

3 个答案:

答案 0 :(得分:2)

您无法使用Ajax上传文件。您必须具有表单属性enctype="multipart/form-data"并使用普通的html请求提交表单。要避免页面刷新,您可以使用iframe。

有像https://blueimp.github.io/jQuery-File-Upload/这样的jquery插件 与php集成,你可以解决你的问题

答案 1 :(得分:1)

此示例包含进度条:

HTML:

AJAX图像上传

<form id="image_upload_form" enctype="multipart/form-data" method="post">
    <input type='file' name='file' maxlength='1' id="image1" accept="image/jpg,image/png,image/jpeg,image/gif" /> <br />
    <input type='file' name='file' maxlength='1' id="image2" accept="image/jpg,image/png,image/jpeg,image/gif" /> <br />
    <input type='file' name='file' maxlength='1'  id="image3" accept="image/jpg,image/png,image/jpeg,image/gif" /> <br />


    <br />
    <br />
    <br />

    <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
    <h3 id="status"></h3>
    <p id="loaded_n_total"></p>


    <input type="button" value="Upload File" onclick="uploadFile()">
</form>

使用Javascript:

    function _(elementID)
    {
        return document.getElementById(elementID);
    }
    function uploadFile()
    {
        var formdata = new FormData();
        var file = _("image1").files[0];
        if (file == 'undefined') {
            alert('file not selected');
            return false;
        }
        formdata.append("file[]", file);

        var file = _("image2").files[0];
        if (file != 'undefined') {

            formdata.append("file[]", file);
        }
        var file = _("image3").files[0];
        if (file != 'undefined') {

            formdata.append("file[]", file);
        }
        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener("progress", myProgressHandler, false);
        ajax.addEventListener("load", myCompleteHandler, false);
        ajax.addEventListener("error", myErrorHandler, false);
        ajax.addEventListener("abort", myAbortHandler, false);
        ajax.open("POST", "file_upload_parser.php");
        ajax.send(formdata);
    }

    function myProgressHandler(event)
    {
        _("loaded_n_total").innerHTML =
                "Uploaded " + event.loaded + " bytes of " + event.total;
        var percent = (event.loaded / event.total) * 100;
        _("progressBar").value = Math.round(percent);
        _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
    }
    function myCompleteHandler(event)
    {
        _("status").innerHTML = event.target.responseText;
        _("progressBar").value = 0;
    }
    function myErrorHandler(event)
    {
        _("status").innerHTML = "Upload Failed";
    }
    function myAbortHandler(event)
    {
        _("status").innerHTML = "Upload Aborted";
    }

和php文件&#34; file_upload_parser.php&#34;:

<pre>
    <?php 

        print_r($_FILES);
    ?>
</pre>

答案 2 :(得分:0)

尝试使用此代码进行多个图像文件上传..  对于html表单..

 <form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
  <input type="submit" value="Upload!" />
</form>

PHP代码将是......

<?php
$valid_formats = array("jpg", "png", "gif", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
    // Loop $_FILES to exeicute all files
    foreach ($_FILES['files']['name'] as $f => $name) {     
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            }
            else{ // No error found! Move uploaded files 
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
                $count++; // Number of successfully uploaded file
            }
        }
    }
}
?>