首页  >  文章  >  后端开发  >  如何在不阻塞服务器和客户端的情况下实时读取和回显服务器当前正在写入的上传文件大小?

如何在不阻塞服务器和客户端的情况下实时读取和回显服务器当前正在写入的上传文件大小?

DDD
DDD原创
2024-10-20 22:02:30758浏览

How to Read and Echo Currently Writing Size of Uploaded File in Server in Realtime Without Blocking Server and Client?

如何在不阻塞服务器和客户端的情况下,实时读取和打印正在服务器端写入的上传文件的大小?

让我们展开来讨论这个问题:

为了实时获取文件上传的进度,我们在 POST 请求中通过 fetch() 从 Blob、File、TypedArray 或 ArrayBuffer 对象设置了 body 对象。

目前的实现将 File 对象设置为 fetch() 的第二个参数传递给 body 对象。

需求:

作为 text/event-stream 读取正在写入服务器文件系统的文件的大小并将其回显到客户端。当 GET 请求中 var 查询字符串参数提供的所有字节都写入完成后停止。文件读取目前在单独的脚本环境中进行,其中 GET 调用向读取文件的脚本发出调用,然后 POST 到将文件写入服务器的脚本。

在完成文件大小回显部分后再尝试解决处理服务器端文件写入或文件读取以获取当前文件大小的潜在问题。

目前尝试使用 php 满足要求。不过也对 c、bash、nodejs、python 或其他语言或方法感兴趣,这些语言或方法可以用来执行相同任务。

客户端 javascript 部分没问题。只是不太精通 php(世界上使用最广泛的服务器端语言之一),无法在不包含不必要的零件的情况下实施该模式。

动机:

fetch 的进度指示器?

相关:

带有 ReadableStream 的 Fetch

问题:

获得

PHP Notice:  Undefined index: HTTP_LAST_EVENT_ID in stream.php on line 7

在终端。

此外,如果将

while(file_exists($_GET["filename"]) 
  &amp;&amp; filesize($_GET["filename"]) < intval($_GET["filesize"]))

替换为

while(true)

它会在 EventSource 处产生错误。

没有 sleep() 调用,正确的文件大小会分发到一个大小为 3.3MB 的文件的消息事件中,3321824、61921、26214 和 38093 分别在上传同一文件三次时被打印出来。预期结果是在以下位置写入文件时获取文件大小:

stream_copy_to_stream($input, $file);

而不是上传的文件对象的 filesize。fopen() 或 stream_copy_to_stream() 是否会阻止其他 php process 访问 stream.php?

到目前为止尝试的方法:

php 引用自

  • 超越 $_POST、$_GET 和 $_FILE:在 JavaScriptPHP 中处理 Blob
  • 具有 PHP 示例的 Server-Sent Events 简介

php

// 能否合并 `data.php`、`stream.php` 为同一个文件?
// 能否使用 `STREAM_NOTIFY_PROGRESS` 
// "Indicates current progress of the stream transfer 
// in bytes_transferred and possibly bytes_max as well" to read bytes?
// do we need to call `stream_set_blocking` to `false`
// data.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";

?>
// stream.php
<?php

  header("Content-Type: text/event-stream");
  header("Cache-Control: no-cache");
  header("Connection: keep-alive");
  // `PHP Notice:  Undefined index: HTTP_LAST_EVENT_ID in stream.php on line 7` ?
  $lastId = $_SERVER["HTTP_LAST_EVENT_ID"] || 0;
  if (isset($lastId) &amp;&amp; !empty($lastId) &amp;&amp; is_numeric($lastId)) {
      $lastId = intval($lastId);
      $lastId++;
  }
  // else {
  //  $lastId = 0;
  // }

  // while current file size read is less than or equal to 
  // `$_GET["filesize"]` of `$_GET["filename"]`
  // how to loop only when above is `true`
  while (true) {
    $upload = $_GET["filename"];
    // is this the correct function and variable to use
    // to get written bytes of `stream_copy_to_stream($input, $file);`?
    $data = filesize($upload);
    // $data = $_GET["filename"] . " " . $_GET["filesize"];
    if ($data) {
      sendMessage($lastId, $data);
      $lastId++;
    } 
    // else {
    //   close stream 
    // }
    // not necessary here, though without thousands of `message` events
    // will be dispatched
    // sleep(1);
    }

    function sendMessage($id, $data) {
      echo "id: $id\n";
      echo "data: $data\n\n";
      ob_flush();
      flush();
    }
?>

javascript

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="file">
<progress value="0" max="0" step="1"></progress>
<script>

const [url, stream, header] = ["data.php", "stream.php", "x-filename"];

const [input, progress, handleFile] = [
        document.querySelector("input[type=file]")
      , document.querySelector("progress")
      , (event) => {
          const [file] = input.files;
          const [{size:filesize, name:filename}, headers, params] = [
                  file, new Headers(), new URLSearchParams()
                ];
          // set `filename`, `filesize` as search parameters for `stream` URL
          Object.entries({filename, filesize})
          .forEach(([...props]) => params.append.apply(params, props));
          // set header for `POST`
          headers.append(header, filename);
          // reset `progress.value` set `progress.max` to `filesize`
          [progress.value, progress.max] = [0, filesize];
          const [request, source] = [
            new Request(url, {
                  method:"POST", headers:headers, body:file
                })
            // https://stackoverflow.com/a/42330433/
          , new EventSource(`${stream}?${params.toString()}`)
          ];
          source.addEventListener("message", (e) => {
            // update `progress` here,
            // call `.close()` when `e.data === filesize` 
            // `progress.value = e.data`, should be this simple
            console.log(e.data, e.lastEventId);
          }, true);

          source.addEventListener("open", (e) => {
            console.log("fetch upload progress open");
          }, true);

          source.addEventListener("error", (e) => {
            console.error("fetch upload progress error");
          }, true);
          // sanity check for tests, 
          // we don't need `source` when `e.data === filesize`;
          // we could call `.close()` within `message` event handler
          setTimeout(() => source.close(), 30000);
          // we don't need `source' to be in `Promise` chain, 
          // though we could resolve if `e.data === filesize`
          // before `response`, then wait for `.text()`; etc.
          // TODO: if and where to merge or branch `EventSource`,
          // `fetch` to single or two `Promise` chains
          const upload = fetch(request);
          upload
          .then(response => response.text())
          .then(res => console.log(res))
          .catch(err => console.error(err));
        }
];

input.addEventListener("change", handleFile, true);
</script>
</body>
</html>

以上是如何在不阻塞服务器和客户端的情况下实时读取和回显服务器当前正在写入的上传文件大小?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn