我试图通过AJAX、XMLHttpRequest和PHP上传视频文件以显示上传进度,但如果我试图上传内容,请求会抛出中止并快速刷新页面。
如果我只是通过表单向PHP文件发送POST请求,而没有AJAX/XMLHttpRequest,那么文件上传就可以了。但是进度条会很方便。。。
代码由HTML表单、JavaScript函数和PHP上传组成(我省略了进度条HTML代码,使其更具可读性(
HTML:
<form action="" method="post" enctype="multipart/form-data" id="uploadForm">
<input type="file" accept="video/mp4" class="form-control" name="fileToUpload" id="fileToUpload" onclick="closeFileToBigAlert()" onchange="checkFile(this.files)" required>
<button onclick="uploadFile()" class="btn">Upload</button>
</form>
JavaScript:
function uploadFile(){
// Get the file
var file = document.getElementById("fileToUpload").files[0];
// Create FormData object and append file as "file"
var formData = new FormData();
formData.append("file",file);
// Create XMLHttpRequest object
var ajax = new XMLHttpRequest();
// Add Event Listeners
ajax.upload.addEventListener("upload-progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
// Open upload.php and send POST request
ajax.open("POST", "upload.php");
ajax.send(formData);
}
function progressHandler(event){
// Calculate percentage
var percent = (event.loaded / event.total) * 100;
// Insert percentage number into progress bar
var bar = document.getElementById("upload-progress");
bar.setAttribute("aria-valuenow", Math.round(percent));
bar.setAttribute("style", "width: "+ Math.round(percent) +"%");
bar.innerHTML = Math.round(percent) + "%";
}
function completeHandler(event){
document.getElementById("status").innerHTML = event.target.responseText;
var bar = document.getElementById("upload-progress");
bar.setAttribute("aria-valuenow", "0");
bar.setAttribute("style", "width: 0%");
bar.innerHTML = "0%";
}
function errorHandler(event){
document.getElementById("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
document.getElementById("status").innerHTML = "Upload Aborted";
}
和PHP:
$fileName = $_FILES["file"]["name"];
$fileTmpLoc = $_FILES["file"]["tmp_name"];
$fileType = $_FILES["file"]["type"];
$fileSize = $_FILES["file"]["size"];
$fileErrorMsg = $_FILES["file"]["error"];
if(move_uploaded_file($fileTmpLoc, "uploads/$fileName")){
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
你知道为什么请求会立即中止并刷新页面吗?PHP日志为空。
环境是通过XAMPP 本地的
您正在提交表单。JS启动,但随后表单提交,然后您导航到一个新页面(这会中止上一页的所有JS(。
- 删除
onclick
属性 - 在表单上绑定提交事件处理程序
- 防止表单提交时出现默认行为
例如:
document.querySelector(`#uploadForm`).addEventListener('submit', event => {
event.preventDefault();
// Do everything else
});