使用 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">
JavaScript(添加文件):
$(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中文网其他相关文章!