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

Riv*_*nat 45 php ajax jquery multi-upload jquery-file-upload

我设计了一个简单的表单,允许用户将文件上传到服务器.最初,表单包含一个"浏览"按钮.如果用户想要上传多个文件,他需要点击"添加更多文件"按钮,在该表单中添加另一个"浏览"按钮.提交表单后,文件上载过程将在"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>
Run Code Online (Sandbox Code Playgroud)

这是JavaScript:

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

以下是处理文件上传的代码:

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 />";
}
Run Code Online (Sandbox Code Playgroud)

}

关于如何编写'.submit()'函数的任何建议都会非常有用.

Riv*_*nat 55

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

$('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;
});
Run Code Online (Sandbox Code Playgroud)

  • Kalai的回答会产生多个错误.这就是我不接受的原因.但是当他试图帮助时,我很高兴和感激他. (16认同)
  • 很好很简单的解决方案,虽然你在上面发布的代码中错过了一个; 在末尾.. (2认同)

Kal*_*lai 47

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>
Run Code Online (Sandbox Code Playgroud)

使用Javascript

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

用于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) {

             }       
             });
            }
        });
Run Code Online (Sandbox Code Playgroud)

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. 
*/
Run Code Online (Sandbox Code Playgroud)

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

  • @kalai对于var"filedata = document.getElementsByName("file"),它显示错误"filedata.files is undefined";" (3认同)
  • 仍为"var i = 0,len = filedata.files.length,img,reader,file;"显示"TypeError:filedata.files is undefined". (2认同)
  • @Kalai:显示此错误"showUploadedItem未定义".我该怎么做才能解决这个问题? (2认同)
  • 它还在重新加载我的页面 (2认同)