实时读取并回显上传文件的文件大小
问题:
如何实时读取并回显正在写入服务器的上传文件的文件大小,而不阻塞服务器和客户端?
解决方案:
服务器(例如PHP):
<code class="php"><?php $filename = $_SERVER["HTTP_X_FILENAME"]; $input = fopen("php://input", "rb"); $file = fopen($filename, "wb"); stream_copy_to_stream($input, $file); fclose($input); fclose($file); echo "upload of " . $filename . " successful"; ?></code>
<code class="php"><?php header("Content-Type: text/event-stream"); header("Cache-Control: no-cache"); header("Connection: keep-alive"); $filename = $_GET["filename"]; $filesize = $_GET["filesize"]; clearstatcache(true, $filename); $data = filesize($filename); while ($data < $filesize) { sendMessage($data); clearstatcache(true, $filename); $data = filesize($filename); usleep(20000); } function sendMessage($data) { echo "data: $data\n\n"; flush(); } ?></code>
客户端(例如 JavaScript):
<code class="javascript">const handleFile = (event) => { const [file] = input.files; const headers = new Headers(); headers.append("x-filename", file.name); const request = new Request("data.php", { method: "POST", headers: headers, body: file, }); fetch(request); startSSE(file.name, file.size); };</code>
<code class="javascript">function startSSE(filename, filesize) { const source = new EventSource(`stream.php?filename=${filename}&filesize=${filesize}`); source.addEventListener("message", (e) => { const data = parseInt(e.data); progress.value = data; }); }</code>
安全注意事项:
以上是如何实时监控和回显上传文件的文件大小,同时防止服务器和客户端阻塞?的详细内容。更多信息请关注PHP中文网其他相关文章!