Reading and Echoing File Size of Uploaded Files in Real Time
Issue:
How to read and echo the file size of an uploaded file being written to the server in real time without blocking both the server and client?
Solution:
Server (e.g., 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>
Client (e.g., 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>
Security Considerations:
The above is the detailed content of How to Monitor and Echo File Size of Uploaded Files in Real Time While Preventing Server and Client Blocking?. For more information, please follow other related articles on the PHP Chinese website!