PHP上传大文件并显示上传进度
#首先需要修改php.ini参数
upload_max_filesize = 50M #设置允许上传的最大文件大小
post_max_size = 60M #设置 POST 数据的最大大小(包括上传的文件)
memory_limit = 128M #设置脚本可以使用的最大内存量
max_execution_time = 300 #设置脚本的最大执行时间(秒)
max_input_time = 300 #设置脚本解析输入数据的最大时间(秒)
#修改nginx.conf文件,在http或server模块下添加如下代码
client_max_body_size 50M; # 设置允许的最大请求体大小
$("#fileForm").on("submit", function(e){
e.preventDefault();
const formData = new FormData(this);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/media/file-store', true);
xhr.setRequestHeader("X-CSRF-TOKEN", $('meta[name="csrf-token"]').attr('content'));
// 监听上传进度事件
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
$('#progress').css('width', percentComplete + '%');
$('#progress').text(Math.round(percentComplete) + '%');
}
};
// 监听上传完成事件
xhr.onload = function() {
if (xhr.readyState==4 && xhr.status === 200 ) {
var result = JSON.parse(xhr.responseText)
if(result.errno === 0){
window.location.reload();
}else{
alert(result.message);
}
} else {
alert('File upload failed!');
}
};
// 发送请求
xhr.send(formData);
});
<form id="fileForm" method="POST" enctype="multipart/form-data">
<div class="mb-3">
<label class="form-label">文件</label><br>
<input type="file" name="file" value="">
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
<div id="progressBar" style="width: 100%; background-color: #ddd;">
<div id="progress" style="height: 30px; width: 0%; background-color: #4caf50; text-align: center; line-height: 30px; color: white;">
0%
</div>
</div>