注意我是PHP,Apache和服务器编程的新手,因此我们将不胜感激。
我在javascript中创建了一个进度条,用于在上传文件时显示。当前我以设定的帧速率更新进度条(以查看它是否有效)。
显然,为了使其成为一个准确的进度条,一切都应该与传输的字节数相比,与总字节数相比较。
使用PHP5如何获取有关与文件总字节数相关的传输字节数的信息,以便我可以将其传递给JS函数updateProgress(bytesSoFar, totalBytes)
来更新我的进度条?请详细告诉我下面代码所需的修改,以使其工作。我看过xhr
个例子,但它们无法完全访问。
我刚刚设置了LocalHost并正在使用W3Schools的PHP File Upload教程。为了使模拟的“上传”工作,我改变了本S.O中建议的本地权限。 post。我不一定需要读取文件,我只想知道已经传输了很多字节。
目前我有两个文件:
的index.php
upload.php的
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$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.";
}
}
?>
我找到了这段代码:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
// move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
move_uploaded_file($_FILES["userfile"]["tmp_name"], "uploads/" . $_FILES["userfile"]["name"]);
}
?>
<html>
<head>
<title>File Upload Progress Bar</title>
<style type="text/css">
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}
#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}
#bar_blank, #hidden_iframe {
display: none;
}
</style>
</head>
<body>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<div id="status"></div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" id="myForm" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
</form>
<script type="text/javascript">
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php");
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";
if (response < 100) {
setTimeout("sendRequest()", 1000);
}
else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
}
}
}
function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
document.getElementById("myForm").onsubmit = startUpload;
})();
</script>
</body>
</html>
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
$message = ceil($current / $total * 100) : 100;
$message = "$message"
echo "<script type='text/javascript'>alert('$message');</script>";
}
else {
echo 100;
}
?>
与我之前的代码一样,传输文件。但是,直到结束时才会显示字节(即使它应该提醒它),它也会打开一个带有“完成”的新窗口。上一个窗口中的陈述。
答案 0 :(得分:4)
如果您坚持使用Php来显示进度,可以查看此Php File Upload Progress Bar,这可能有助于您入门。这使用PECL扩展APC来获取上载的文件进度详细信息。可以使用响应来计算服务器接收的字节数
根据第一个链接 apc_fetch()
。
另一个有趣的Track Upload Progress教程,它使用了Php的原生Session Upload Progress功能。
最后,如果您对使用Javascript(或JS库)有点开放,那将是理想。我知道的一个易于使用,易于设置,众所周知和维护的库是FineUploader
答案 1 :(得分:1)
您可以使用Session Upload Progress功能。它是原生的,但需要一些php.ini配置。
请查看PHP manual。
更新1
注意,您无需更改upload.php。您可以创建一个新的php文件(例如progress.php)并向他们发出请求,以检查您的JS上传进度。
<强> progress.php 强>
<?php
$upload_id = $_GET['upload_id];
print json_encode($_SESSION['upload_progress_'.$upload_id]);
然后你的JS会向progress.php?upload_id=YourIdValue
发出GET请求,你会收到一个包含所有进度信息的JSON。