如何上传使用PHP,jQuery和AJAX多个文件

问题描述:

我设计了一个简单的形式,它允许用户将文件上传到服务器。最初的形式包含一个浏览按钮。如果用户要上传多个文件,他需要点击添加更多文件按钮,这又增加了一个浏览按钮的形式。当表单提交,文件上传过程中的upload.php的文件处理。它完美罚款上传多个文件。现在,我需要使用jQuery的提交表单.submit(),并发出AJAX ['阿贾克斯()']请求'upload.php的文件处理文件上传。

I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload.

下面是我的HTML表单:

Here is my HTML form :

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" id="upload" value="Upload File" />
</form>

下面是JavaScript:

Here is the JavaScript :

$(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file' />");
    });
});

下面是code处理文件上传:

Here is the code for processing file upload :

for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
    echo "The file has been uploaded successfully <br />";
} else{
    echo "There was an error uploading the file, please try again! <br />";
}

}

这是我应该怎么写我'.submit()函数的任何建议,将是非常有帮助的。

Any suggestions on how I should write my '.submit()' function will be really helpful.

最后,我已经找到了解决方案,通过使用下面的code:

Finally I have found the solution by using the following code:

$('body').on('click', '#upload', function(e){
        e.preventDefault();
        var formData = new FormData($(this).parents('form')[0]);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            success: function (data) {
                alert("Data Uploaded: "+data);
            },
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
})