實時讀取並回顯上傳文件的文件大小
問題:
如何即時讀取並回顯正在寫入伺服器的上傳檔案的檔案大小,而不阻塞伺服器和客戶端?
解決方案:
伺服器(例如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中文網其他相關文章!