Muat Naik Berbilang Fail Dikuasakan Ajax dengan PHP, jQuery dan AJAX
Untuk memuat naik berbilang fail menggunakan PHP, jQuery dan AJAX, ikuti langkah berikut:
HTML Borang:
<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 (Tambah Fail):
$(document).ready(function() { $('.add_more').click(function(e) { e.preventDefault(); $(this).before("<input name='file[]' type='file' />"); }); });
JavaScript (Muat Naik Fail):
$('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; });
Muat Naik Fail PHP Pemprosesan:
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 />"; } }
Kod ini menyelaraskan proses memuat naik berbilang fail melalui permintaan Ajax.
Atas ialah kandungan terperinci Bagaimana untuk Melaksanakan Muat Naik Berbilang Fail Dikuasakan Ajax dengan PHP, jQuery dan AJAX?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!