gpt4 book ai didi

javascript - 使用 PHP5 为 POST 请求传输字节

转载 作者:可可西里 更新时间:2023-11-01 02:10:21 25 4
gpt4 key购买 nike

注意我是 PHP、Apache 和服务器编程的新手,因此将不胜感激更详尽的解释。


上下文

我在 javascript 中创建了一个在上传文件时显示的进度条。目前,我以设定的帧速率更新进度条(以查看它是否有效)。

很明显,要使其成为一个准确的进度条,所有内容都应与传输的字节数与总字节数的比较有关。

问题

使用 PHP5 我怎样才能获得有关传输的字节数与文件总字节数的相关信息,以便我可以将其传递给 JS 函数 updateProgress(bytesSoFar, totalBytes) 更新我的进度条?请详细地指导我完成以下代码所需的修改以使其正常工作。我看过 xhr 示例,但它们并不完全可用。

我刚刚设置了LocalHost并且正在使用 W3Schools 的 PHP File Upload教程。为了让模拟的“上传”工作,我按照这个 S.O. 中的建议更改了本地权限。 post .我不一定需要读取文件,我只想知道已经传输了多少字节。


代码

目前我有两个文件:

  • index.php

  • upload.php

索引.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

<?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

<?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>

进度.php

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;
}
?>

与我之前的代码一样,它传输文件。但是,这直到最后才显示字节(即使它应该对此发出警报),它还会打开一个带有“完成”的新窗口。在前一个窗口中声明。

最佳答案

你可以看看这个 Php File Upload Progress Bar如果您坚持使用 Php 显示进度,这可能会帮助您入门。这使用 PECL 扩展 APC获取上传文件进度详细信息。可以使用以下响应计算服务器接收到的字节数apc_fetch() 根据第一个链接。

另一个有趣的Track Upload Progress使用 Php 原生的教程 Session Upload Progress功能。

最后,如果您愿意使用 Javascript(或 JS 库),那将是理想。我知道一个易于使用、易于设置、众所周知且维护良好的库是 FineUploader

关于javascript - 使用 PHP5 为 POST 请求传输字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42467077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com