php+html+js+ajax实现文件上传
目录
一、表单单文件上传
1、上传页面
2、接受文件上传php
二、表单多文件上传
1、上传页面
2、接受文件上传php
三、表单异步xhr文件上传
1、上传页面
2、接受文件上传php
四、表单异步ajax文件上传
1、上传页面
2、接受文件上传php
一、表单单文件上传
1、上传页面
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head><title>文件上传</title>
</head>
<body>
<h1>文件上传</h1>
<form action="upload.php" method="POST" enctype="multipart/form-data"><input type="file" name="fileToUpload"><input type="submit" value="上传文件">
</form>
</body>
</html>
2、接受文件上传php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {$targetDir = "uploads/"; // 上传文件保存的目录$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);$uploadOk = 1; // 上传状态,1表示成功,0表示失败$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // 上传文件的扩展名// 检查文件是否为真实的图像文件if (isset($_POST["submit"])) {$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);if ($check !== false) {echo "文件是一个有效的图像 - " . $check["mime"] . ".";$uploadOk = 1;} else {echo "文件不是一个有效的图像.";$uploadOk = 0;}}// 检查文件是否已存在if (file_exists($targetFile)) {echo "对不起,文件已存在.";$uploadOk = 0;}// 检查文件大小if ($_FILES["fileToUpload"]["size"] > 500000) {echo "对不起,文件太大.";$uploadOk = 0;}// 允许上传的文件格式$allowedExtensions = array("jpg", "jpeg", "png", "gif");if (!in_array($imageFileType, $allowedExtensions)) {echo "对不起,仅允许上传 JPG, JPEG, PNG 和 GIF 文件.";$uploadOk = 0;}// 检查上传状态if ($uploadOk == 0) {echo "对不起,文件上传失败.";} else {if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {echo "文件上传成功.";} else {echo "对不起,文件上传失败.";}}
}
?>
二、表单多文件上传
1、上传页面
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head><title>文件上传示例</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data"><input type="file" name="files[]" multiple><input type="submit" value="上传文件">
</form>
</body>
</html>
2、接受文件上传php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {$files = $_FILES["files"];// 检查是否有文件被上传if (!empty($files)) {// 循环处理每个上传的文件for ($i = 0; $i < count($files["name"]); $i++) {$file_name = $files["name"][$i];$file_tmp = $files["tmp_name"][$i];$file_size = $files["size"][$i];$file_error = $files["error"][$i];// 检查文件是否上传成功if ($file_error == UPLOAD_ERR_OK) {// 指定文件保存的路径和文件名$target_dir = "uploads/";$target_file = $target_dir . basename($file_name);// 将文件从临时目录移动到指定路径if (move_uploaded_file($file_tmp, $target_file)) {echo "文件上传成功: " . $file_name . "<br>";} else {echo "文件上传失败: " . $file_name . "<br>";}} else {echo "文件上传错误: " . $file_name . "<br>";}}} else {echo "没有选择要上传的文件";}
}
?>
三、表单异步xhr文件上传
1、上传页面
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head><title>文件上传</title>
</head>
<body>
<h1>文件上传</h1>
<input type="file" id="fileToUpload" multiple>
<button onclick="uploadFiles()">上传文件</button>
<div id="progress"></div>
<div id="response"></div><script>function uploadFiles() {var input = document.getElementById('fileToUpload');var files = input.files;var formData = new FormData();for (var i = 0; i < files.length; i++) {var file = files[i];formData.append('files[]', file);}var xhr = new XMLHttpRequest();xhr.onreadystatechange = function() {if (xhr.readyState === 4 && xhr.status === 200) {document.getElementById('response').innerHTML = xhr.responseText;}};xhr.upload.onprogress = function(event) {if (event.lengthComputable) {var progress = (event.loaded / event.total) * 100;document.getElementById('progress').innerHTML = '上传进度:' + progress + '%';}};xhr.open('POST', 'upload.php', true);xhr.send(formData);}
</script>
</body>
</html>
2、接受文件上传php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {$targetDir = "uploads/"; // 上传文件保存的目录if (!file_exists($targetDir)) {mkdir($targetDir, 0777, true); // 如果目录不存在,则创建目录}$uploadOk = 1; // 上传状态,1表示成功,0表示失败foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {$targetFile = $targetDir . $_FILES['files']['name'][$key];$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // 上传文件的扩展名// 检查文件是否已存在if (file_exists($targetFile)) {echo "对不起,文件已存在.";$uploadOk = 0;}// 允许上传的文件格式$allowedExtensions = array("jpg", "jpeg", "png", "gif");if (!in_array($imageFileType, $allowedExtensions)) {echo "对不起,仅允许上传 JPG, JPEG, PNG 和 GIF 文件.";$uploadOk = 0;}// 检查上传状态if ($uploadOk == 0) {echo "对不起,文件上传失败.";} else {if (move_uploaded_file($tmp_name, $targetFile)) {echo "文件上传成功.";} else {echo "对不起,文件上传失败.";}}}
}
?>
四、表单异步ajax文件上传
1、上传页面
<!DOCTYPE html>
<html><meta charset="UTF-8">
<head><title>文件上传示例</title><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data"><input type="file" name="fileToUpload" id="fileToUpload"><button type="submit">上传</button>
</form><script>$(document).ready(function() {$('#uploadForm').submit(function(event) {event.preventDefault();var formData = new FormData(this);$.ajax({url: 'upload.php',type: 'POST',data: formData,dataType: 'text',processData: false,contentType: false,success: function(response) {console.log('文件上传成功');},error: function() {console.log('文件上传失败');}});});});
</script>
</body>
</html>
2、接受文件上传php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {if (isset($_FILES['fileToUpload'])) {$file = $_FILES['fileToUpload'];// 文件上传成功if ($file['error'] === UPLOAD_ERR_OK) {$fileName = $file['name'];$tempPath = $file['tmp_name'];// 将文件移动到目标文件夹move_uploaded_file($tempPath, 'uploads/' . $fileName);echo '文件上传成功';} else {echo '文件上传失败';}} else {echo '未选择文件';}
}
?>