为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白板的微信 2019-09-20 17:13:12
我设计了一个简单的表单,允许用户将文件上传到服务器。最初,表单包含一个“浏览”按钮。如果用户想要上传多个文件,他需要点击“添加更多文件”按钮,在该表单中添加另一个“浏览”按钮。提交表单后,文件上载过程将在“upload.php”文件中处理。它适用于上传多个文件。现在我需要使用jQuery的'.submit()'提交表单,并将'ajax ['.ajax()']请求发送到'upload.php'文件来处理文件上传。这是我的HTML表单:<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:$(document).ready(function(){    $('.add_more').click(function(e){        e.preventDefault();        $(this).before("<input name='file[]' type='file' />");    });});以下是处理文件上传的代码: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()'函数的任何建议都会非常有用。
查看完整描述

3 回答

?
MM们

TA贡献1886条经验 获得超2个赞

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


$('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;

});


查看完整回答
反对 回复 2019-09-20
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

HTML


<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" value="Upload File" id="upload"/>

</form>

使用Javascript


 $(document).ready(function(){

    $('.add_more').click(function(e){

        e.preventDefault();

        $(this).before("<input name='file[]' type='file'/>");

    });

});

用于ajax上传


$('#upload').click(function() {

    var filedata = document.getElementsByName("file"),

            formdata = false;

    if (window.FormData) {

        formdata = new FormData();

    }

    var i = 0, len = filedata.files.length, img, reader, file;


    for (; i < len; i++) {

        file = filedata.files[i];


        if (window.FileReader) {

            reader = new FileReader();

            reader.onloadend = function(e) {

                showUploadedItem(e.target.result, file.fileName);

            };

            reader.readAsDataURL(file);

        }

        if (formdata) {

            formdata.append("file", file);

        }

    }

    if (formdata) {

        $.ajax({

            url: "/path to upload/",

            type: "POST",

            data: formdata,

            processData: false,

            contentType: false,

            success: function(res) {


            },       

            error: function(res) {


             }       

             });

            }

        });

PHP


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 />";

    }

}


/** 

    Edit: $target_path variable need to be reinitialized and should 

    be inside for loop to avoid appending previous file name to new one. 

*/

请使用上面的脚本脚本进行ajax上传。它会工作


查看完整回答
反对 回复 2019-09-20
?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

我的解决方案


假设表单id =“my_form_id”

它从HTML中检测表单方法和表单操作

jQuery代码


$('#my_form_id').on('submit', function(e) {

    e.preventDefault();

    var formData = new FormData($(this)[0]);

    var msg_error = 'An error has occured. Please try again later.';

    var msg_timeout = 'The server is not responding';

    var message = '';

    var form = $('#my_form_id');

    $.ajax({

        data: formData,

        async: false,

        cache: false,

        processData: false,

        contentType: false,

        url: form.attr('action'),

        type: form.attr('method'),

        error: function(xhr, status, error) {

            if (status==="timeout") {

                alert(msg_timeout);

            } else {

                alert(msg_error);

            }

        },

        success: function(response) {

            alert(response);

        },

        timeout: 7000

    });

});


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 938 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信