Uploading Multiple Images Using AJAX, PHP, and jQuery
In this discussion, the issue of uploading multiple images using AJAX techniques is addressed. The user describes having encountered difficulties in transmitting multiple files via AJAX, leading to incomplete file delivery. This article provides a comprehensive solution that leverages JSON to efficiently process the file object and facilitate successful upload.
HTML
The following HTML code establishes the structure of the web page, including elements for drag-and-drop functionality, the file input, and sections for displaying upload progress and results:
<div>
CSS
Styling is applied to enhance the user interface and provide visual cues during the file upload process:
#uploads { display: block; position: relative; } #uploads li { list-style: none; }
JavaScript
The JavaScript code handles the file upload process, leveraging AJAX to communicate with the server. It utilizes JSON to encapsulate file data and HTML5 techniques for progress tracking:
$(document).on("change", "input[name^='file']", function (e) { e.preventDefault(); var This = this, display = $("#uploads"); // process file object $.each(This.files, function (i, file) { var reader = new FileReader(), dfd = new $.Deferred(); reader.onload = function (e) { // convert file to data URL dfd.resolveWith(file, [e.target.result]) }; reader.readAsDataURL(new Blob([file], { "type": file.type })); dfd.then(function (data) { // send file data using AJAX $.ajax({ url: "/echo/json/", type: "POST", data: { "file": JSON.stringify({ "file": data, "name": file.name, "size": file.size, "type": file.type }) } }) .then(function (data, textStatus, jqxhr) { console.log(data) display.append("<br /><li>", img, "</li><br />"); return data }, function (jqxhr, textStatus, errorThrown) { console.log(errorThrown); return errorThrown }); }) }); });
PHP
The PHP script receives the file data encoded in JSON format and returns it as a JSON string:
<?php if (isset($_POST["file"])) { // process file object $file = json_encode($_POST["file"]); // return file as JSON string echo $file; }; ?>
By implementing these techniques, you can efficiently upload multiple images using AJAX, PHP, and jQuery. The JSON approach simplifies file transmission, and the use of progress tracking enhances the user experience by providing real-time feedback on the upload status.
The above is the detailed content of How can I efficiently upload multiple images using AJAX, PHP, and jQuery?. For more information, please follow other related articles on the PHP Chinese website!