Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-23 05:54:14
Original
777 people have browsed it

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">
Copy after login

JavaScript (Add File):

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

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;
});
Copy after login

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template