Home  >  Article  >  Backend Development  >  How to Implement Ajax-Powered Multiple File Uploads with PHP, jQuery, and AJAX?

How to Implement Ajax-Powered Multiple File Uploads with PHP, jQuery, and AJAX?

Linda Hamilton
Linda HamiltonOriginal
2024-11-23 05:54:14710browse

How to Implement Ajax-Powered Multiple File Uploads with PHP, jQuery, and AJAX?

Ajax-Powered Multiple File Uploads with PHP, jQuery, and AJAX

To upload multiple files using PHP, jQuery, and AJAX, follow these steps:

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

JavaScript (Add File):

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

JavaScript (Upload Files):

$('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 File Upload Processing:

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

This code streamlines the process of uploading multiple files via an Ajax request.

The above is the detailed content of How to Implement Ajax-Powered Multiple File Uploads with PHP, jQuery, and AJAX?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn