使用Ajax实现上传文件的进度,要求使用JQuery来实现。前端和后端代码
时间: 2024-03-09 20:44:28 浏览: 70
基于ajax实现文件上传并显示进度条
5星 · 资源好评率100%
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传文件进度</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label for="file">选择文件:</label>
<input type="file" name="file" id="file"><br>
<input type="button" value="上传" onclick="uploadFile()">
</form>
<div id="progress"></div>
<script>
function uploadFile() {
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var progress = e.loaded / e.total * 100;
$("#progress").text("上传进度: " + progress.toFixed(2) + "%");
}
}, false);
}
return xhr;
},
processData: false,
contentType: false,
success: function(data) {
alert(data);
}
});
}
</script>
</body>
</html>
```
后端代码(使用PHP实现):
```php
<?php
$filename = $_FILES["file"]["name"];
$filetype = $_FILES["file"]["type"];
$filesize = $_FILES["file"]["size"];
$tmp_name = $_FILES["file"]["tmp_name"];
$error = $_FILES["file"]["error"];
if ($error > 0) {
echo "上传错误: " . $error;
} else {
move_uploaded_file($tmp_name, "uploads/" . $filename);
echo "上传成功!";
}
?>
```
这里使用了FormData来获取表单数据,通过ajax将表单数据上传到后端,使用xhr.upload.addEventListener来监听进度并实时更新前端页面上的进度条。后端代码通过move_uploaded_file函数将上传的文件保存到指定目录中。
阅读全文