这是从文件还是浏览器内存流式传输?

Is this streaming from file or browser memory?

在下面的代码中,我似乎可以流式传输本地文件而无需一次将其全部加载到内存中,因为对于较大的文件,我会得到多个块(请参见下面的 console.log(chunk.length);

const fileInput = document.getElementById('file-input');
const startButton = document.getElementById('start-button');

fileInput.addEventListener('change', () => {
  console.log(fileInput.files);
});

startButton.addEventListener('click', () => {
  if (fileInput.files && fileInput.files.length) {
    const fileURL = URL.createObjectURL(fileInput.files[0]);
    fetch(fileURL, {
      method: 'GET',
      cache: 'no-store'
    }).then(response => {
      response.body.pipeTo(
        new WritableStream({
          write: chunk => {
            console.log(chunk.length);
          },
          abort: error => {
            console.error(error);
          },
          close: () => {
            URL.revokeObjectURL(fileURL);
          }
        })
      );
    });
  }
});
<input type="file" id="file-input" />
<button  id="start-button">start</button>

但我想知道的是,const fileURL = URL.createObjectURL(fileInput.files[0]); 创建一个 link 到本地文件,然后通过 ReadableStream 从提取中读取该文件,还是将整个文件加载到浏览器内存中我看到的块是 "artificial" 或从浏览器内存流式传输到 Javascript 虚拟机内存?

URL.createObjectURL( Blob ) 只创建指向 Blob 资源的符号链接。

如果是用户磁盘上的文件,那么它只是磁盘上该文件的符号链接,如果您重命名它或在磁盘上删除它,您的 blob-URI 将指向任何地方。

自己做测试:

let url;
inp.oninput = e => url = URL.createObjectURL( inp.files[0] );
btn.onclick = e => fetch( url )
  .then( console.log )
  .catch( console.error );
<ol>
  <li> select a file <input type="file" id="inp"></li>
  <li> rename it on your disk or delete it</li>
  <li> <button id="btn">try to fetch it</button></li>
</ol>

Ps:如果是内存中的 Blob,它也只是一个符号链接,但它也会将此资源标记为活动的,从而阻止垃圾收集器收集它,直到你撤销这个 blob-URI。