如何使用 PHP、jQuery 和 AJAX 上传多个文件 [英] How to upload multiple files using PHP, jQuery and AJAX

查看:46
本文介绍了如何使用 PHP、jQuery 和 AJAX 上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计了一个简单的表单,允许用户将文件上传到服务器.最初表单包含一个浏览"按钮.如果用户想上传多个文件,他需要点击添加更多文件"按钮,在表单中添加另一个浏览"按钮.当表单被提交时,文件上传过程在'upload.php'文件中处理.它非常适合上传多个文件.现在我需要使用 jQuery 的 '.submit()' 提交表单,并向 'upload.php' 文件发送一个 ajax ['.ajax()'] 请求来处理文件上传.

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

这里是处理文件上传的代码:

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.

推荐答案

最后我通过使用以下代码找到了解决方案:

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

这篇关于如何使用 PHP、jQuery 和 AJAX 上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆