javascript – 如何在服务器和客户端上实时读取和回显正在服务器上写入的上传文件的文件大小?

题:

如何在服务器和客户端上实时读取和回显正在服务器上写入的上传文件文件大小?

语境:

从fetch()发出的POST请求写入服务器的文件上载进度,其中body设置为Blob,File,TypedArray或ArrayBuffer对象.

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

需求:

读取并向客户端回显正在以文本/事件流的形式写入服务器文件系统的文件文件大小.当作为GET请求的查询字符串参数作为脚本变量提供的所有字节都已写入时停止.当前对文件的读取是在一个单独的脚本环境中进行的,其中GET调用脚本应该读取文件是在POST之后发送到脚本,该脚本将文件写入服务器.

没有达到将文件写入服务器或读取文件获取当前文件大小的潜在问题的错误处理,尽管这将是文件大小部分的回声完成后的下一步.

目前正在尝试使用PHP满足要求.虽然也对c,bash,nodejs,python感兴趣;或其他可用于执行相同任务的语言或方法.

客户端javascript部分不是问题.简直就是精通PHP,这是万维网上最常用的服务器端语言之一,用于实现模式而不包括不必要的部分.

动机:

Progress indicators for fetch?

有关:

Fetch with ReadableStream

问题:

入门

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

在码头.

另外,如果替代

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

对于

while(true)

在EventSource上产生错误.

在没有sleep()调用的情况下,当上载相同文件三次时,分别在控制台61921,26214和38093次分别打印正确文件大小为3.3MB文件(3321824)的消息事件.在写入文件时,预期结果是文件文件大小

stream_copy_to_stream($input, $file);

而不是上传文件对象的文件大小. fopen()或stream_copy_to_stream()是否阻止了stream.PHP上的其他PHP进程?

到目前为止尝试过:

PHP归功于

> Beyond $_POST, $_GET and $_FILE: Working with Blob in JavaScriptPHP
> Introduction to Server-Sent Events with PHP example

PHP

// can we merge `data.PHP`, `stream.PHP` to same file?
// can we use `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) && !empty($lastId) && 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>

解决方法:

您需要clearstatcache才能获得真实的文件大小.修复了很少的其他位,您的stream.PHP可能如下所示:

<?PHP

header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");
// 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);
}

function sendMessage($id, $data)
{
    echo "id: $id\n";
    echo "data: $data\n\n";
    ob_flush();
    // no need to flush(). It adds content length of the chunk to the stream
    // flush();
}

几点需要注意:

安全.我的意思是好运.据我所知,它是一个概念证明,安全性是最不重要的问题,但免责声明应该存在.这种方法存在根本缺陷,只有在您不关心DOS攻击或有关文件的信息消失时才应使用.

中央处理器.如果没有睡眠,脚本将消耗单个核心的100%.如果长时间睡眠,您可能会在一次迭代中上传整个文件,并且永远不会满足退出条件.如果您在本地测试它,应该完全删除usleep,因为在本地上传MB是几毫秒.

打开连接. apache和Nginx / fpm都有有限数量PHP进程可以处理请求.单个文件上载将花费2上传文件所需的时间.对于慢带宽或伪造请求,此时间可能很长,并且Web服务器可能会开始拒绝请求.

客户端部分.您需要分析响应并最终在文件完全上载时停止侦听事件.

编辑:

为了使它或多或少生产友好,您需要一个内存存储,如redis或memcache来存储文件元数据.

发出帖子请求,添加标识文件的唯一标记文件大小.

在你的javascript中:

const fileId = Math.random().toString(36).substr(2); // or anything more unique
...

const [request, source] = [
    new Request(`${url}?fileId=${fileId}&size=${filesize}`, {
        method:"POST", headers:headers, body:file
    })
    , new EventSource(`${stream}?fileId=${fileId}`)
];
....

在data.PHP注册令牌并按块报告进度:

....

$fileId = $_GET['fileId'];
$fileSize = $_GET['size'];

setUnique($fileId, 0, $fileSize);

while ($uploaded = stream_copy_to_stream($input, $file, 1024)) {
    updateProgress($id, $uploaded);
}
....


/**
 * Check if Id is unique, and store processed as 0, and full_size as $size 
 * Set reasonable TTL for the key, e.g. 1hr 
 *
 * @param string $id
 * @param int $size
 * @throws Exception if id is not unique
 */
function setUnique($id, $size) {
    // implement with your storage of choice
}

/**
 * Updates uploaded size for the given file
 *
 * @param string $id
 * @param int $processed
 */
function updateProgress($id, $processed) {
    // implement with your storage of choice
}

所以你的stream.PHP根本不需要点击磁盘,只要UX可以接受就可以睡觉:

....
list($progress, $size) = getProgress('non_existing_key_to_init_default_values');
$lastId = 0;

while ($progress < $size) {
    list($progress, $size) = getProgress($_GET["fileId"]);
    sendMessage($lastId, $progress);
    $lastId++;
    sleep(1);
}
.....


/**
 * Get progress of the file upload.
 * If id is not there yet, returns [0, PHP_INT_MAX]
 *
 * @param $id
 * @return array $bytesuploaded, $fileSize
 */
function getProgress($id) {
    // implement with your storage of choice
}

2个打开连接的问题无法解决,除非你放弃了旧的好拉动EventSource.没有循环的stream.PHP的响应时间是几毫秒,并且保持连接始终打开是非常浪费的,除非您每秒需要数百次更新.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...