您好,登錄后才能下訂單哦!
在PHP中,要實現文件上傳進度監控,通常需要以下幾個步驟:
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<br><br>
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
<script>
function uploadFile() {
var fileInput = document.getElementById("fileToUpload");
var formData = new FormData();
formData.append("fileToUpload", fileInput.files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var progress = (event.loaded / event.total) * 100;
console.log("Upload progress: " + progress + "%");
}
}, false);
xhr.open("POST", "upload.php", true);
xhr.send(formData);
}
</script>
現在,當用戶選擇一個文件并點擊上傳按鈕時,uploadFile
函數會被調用。這個函數會創建一個FormData對象,將文件添加到該對象中,并使用XMLHttpRequest發送一個POST請求到服務器。同時,我們監聽了progress
事件,可以在控制臺中查看上傳進度。
請注意,這個示例僅用于演示目的。在實際項目中,你可能需要考慮更多的錯誤處理和安全性問題。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。