使用 PHP、jQuery 和 AJAX 進行 Ajax 驅動的多個檔案上傳
要使用 PHP、jQuery 和 AJAX上傳多個文件,請執行以下操作這些步驟:
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">
Ja vaScript(新增檔案):
$(document).ready(function() { $('.add_more').click(function(e) { e.preventDefault(); $(this).before("<input name='file[]' type='file' />"); }); });
JavaScript(上傳檔案):
$('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 檔案上傳處理:
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 />"; } }
此程式碼簡化了透過 Ajax 請求上傳多個檔案的過程。
以上是如何使用 PHP、jQuery 和 AJAX 實作 Ajax 支援的多個檔案上傳?的詳細內容。更多資訊請關注PHP中文網其他相關文章!