問題:
在不阻塞伺服器的情況下,取得上傳檔案寫入伺服器的即時檔案大小和用戶端。
上下文:
使用帶有文件或 Blob 正文的 fetch() 的 POST 請求寫入伺服器時,客戶端瀏覽器中的文件上傳進度。
要求:
在將檔案大小寫入伺服器檔案系統時將其顯示為文字/事件流。當檔案上傳期間作為查詢字串參數提供的所有位元組都已寫入時停止。目前從單獨的腳本檢索檔案大小,該腳本在檔案寫入伺服器後調用。
實作:
最初嘗試使用 PHP 但遇到了問題由於未定義的 HTTP_LAST_EVENT_ID 和報告的檔案大小不正確而導致的錯誤。也嘗試了不同的方法和語言,如 bash、c、nodejs 和 python。
解決方案:
<code class="php">clearstatcache(true, $upload); $data = filesize($upload);</code>
<code class="php">// Check if the header's been sent to avoid `PHP Notice: Undefined index: HTTP_LAST_EVENT_ID in stream.php on line ` // php 7+ //$lastId = $_SERVER["HTTP_LAST_EVENT_ID"] ?? 0; // php < 7 $lastId = isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? intval($_SERVER["HTTP_LAST_EVENT_ID"]) : 0; $upload = $_GET["filename"]; $data = 0; // if file already exists, its initial size can be bigger than the new one, so we need to ignore it $wasLess = $lastId != 0; while ($data < $_GET["filesize"] || !$wasLess) { // system calls are expensive and are being cached with assumption that in most cases file stats do not change often // so we clear cache to get most up to date data clearstatcache(true, $upload); $data = filesize($upload); $wasLess |= $data < $_GET["filesize"]; // don't send stale filesize if ($wasLess) { sendMessage($lastId, $data); $lastId++; } // not necessary here, though without thousands of `message` events will be dispatched //sleep(1); // millions on poor connection and large files. 1 second might be too much, but 50 messages a second must be okay usleep(20000); }</code>修改
<code class="javascript">const [fileId, request, source] = [ Math.random().toString(36).substr(2), new Request(`${url}?fileId=${fileId}&size=${filesize}`, { method: "POST", headers: headers, body: file }), new EventSource(`${stream}?fileId=${fileId}`) ];</code>修改
<code class="php">function setUnique(string $id, int $size) { // implement with your storage of choice } function updateProgress(string $id, int $processed) { // implement with your storage of choice }</code>修改
<code class="php">list($progress, $size) = getProgress($_GET["fileId"]);</code>修改
修改修改修改
修改以上是如何取得伺服器綁定上傳的即時檔案大小?的詳細內容。更多資訊請關注PHP中文網其他相關文章!